using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using System.IO;
using System.Reflection;
using UnityEngine.UI;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
//using ProtoConfig;
using System.Xml;

using System.Runtime.InteropServices;

public struct TempTextureFormat
{
	public int maxSize; 
	public TextureImporterFormat format;
	public int quality;
    public TextureImporterCompression compression;
}

public static class MaterialTextureForETC1
{
	public static bool isSpace(this Color c, bool alpha)
	{
		if(!alpha)
		{
			if(c.r != 0 || c.g != 0 || c.b != 0)
			{
				return false;
			}
		}
		else
		{
			if(c.a != 0)
			{
				return false;
			}
		}
		return true;
	}
	public const string spriteSheetConfigName = "config.txt";
	public static readonly string[] exts = new string[]
	{
		".png",
		".jpg"
	};

	public const string rgbSuffix = "_RGB";
	public const bool compress = false;
	public const bool isolation = false;
	
//	public static string materialOutputPath = ResourcesEx.BundleResDir + "/Materials";
//	public static string spriteSheetPrefabOutputPath = ResourcesEx.BundleResDir + "/SpriteSheetPrefabs";

    public static float sizeScale = 1f;   //the size decrease scale for alphaTexture
    public static Dictionary<string, bool> texturesAlphaDic = new Dictionary<string, bool>();

	public static Vector4 getSpritePadding(Vector2 pivod, Rect rect, float scale, Rect oldRect)
	{
		oldRect.width *= scale;
		oldRect.height *= scale;

		float offsetx = rect.width * (0.5f - pivod.x);
		float offsety = rect.height * (0.5f - pivod.y);
		
		float subHalfWidth = oldRect.width - rect.width;
		float subHalfHeight = oldRect.height - rect.height;
		subHalfWidth /= 2;
		subHalfHeight /= 2;
		
		float leftSpace = subHalfWidth + offsetx;
		float rightSpace = subHalfWidth - offsetx;
		float bottomSpace = subHalfHeight + offsety;
		float topSpace = subHalfHeight - offsety;
		
		leftSpace = Mathf.Max(0, leftSpace);
		rightSpace = Mathf.Max(0, rightSpace);
		bottomSpace = Mathf.Max(0, bottomSpace);
		topSpace = Mathf.Max(0, topSpace);
		return new Vector4(leftSpace, bottomSpace, rightSpace, topSpace);
	}

	static SpriteInfo getSpriteInfo2(Sprite sprite, float scale, Sprite oldSprite)
	{
		if(oldSprite == null)
		{
			return default(SpriteInfo);
		}
		SpriteInfo info = new SpriteInfo();
		info.pivod = sprite.GetPivot();
		info.border = sprite.border;
		info.rect = sprite.rect;

		info.padding = getSpritePadding(info.pivod, info.rect, scale, oldSprite.rect);

		return info;
	}

	static void SeparateAlpha (string outputPath, bool isDel)
	{
		string[] paths = Directory.GetFiles (outputPath, "*.png", SearchOption.AllDirectories);
		foreach (string path in paths)
		{
			if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
			{
				outputPath = Path.GetDirectoryName(path);
				SeperateRGBAandlphaChannel (path, outputPath);
				System.GC.Collect();
			}
		}

		foreach (string path in paths)
		{
			if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
			{
				if (isDel)
				{
					string rgbTexPath = GetRGBTexPath (path);

					CommonUtil.Move (rgbTexPath, path);
				}
			}
		}
	}

//	public delegate void createSpriteSheetConfigCallBack();
//
//	static IEnumerator createSpriteSheetConfig (string srcPath, BuildTarget target, string outputPath, HashSet<string> hashSet, createSpriteSheetConfigCallBack callBack)
//	{
//		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(srcPath, target.getPlatform());
//
//		for (int m = 0; m < exts.Length; m++)
//		{
//			string[] paths = Directory.GetFiles (outputPath, "*" + exts[m], SearchOption.AllDirectories);
//			foreach (string path in paths)
//			{
//				if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
//				{
//					string spriteSheetName = getSpriteSheetNameBySpriteSheetPath(path);
//					if(hashSet != null)
//					{
//						if(!hashSet.Contains(spriteSheetName))
//						{
//							continue;
//						}
//					}
//
//					SpriteSheetInfo info = null;
//					config.TryGetValue(spriteSheetName, out info);
//
//					string ext = Path.GetExtension(path);
//
//					Object[] objs = AssetDatabase.LoadAllAssetsAtPath (path);
//					Dictionary<string, SpriteInfo> spriteMap = new Dictionary<string, SpriteInfo> ();
//					Texture2D tex = null;
//					float pixelsPerUnit = 100;
//					for (int k = 0; k < objs.Length; k++)
//					{
//						if (objs [k] is Sprite)
//						{
//							Sprite sprite = objs [k] as Sprite;
//
//							string oldSpritePath = sprite.name.Replace(ResourcesEx.dirSymbol, '/');
//							oldSpritePath = srcPath + "/" + oldSpritePath;
//
//							Sprite oldSprite = AssetDatabase.LoadAssetAtPath(oldSpritePath + ext, typeof(Sprite)) as Sprite;
//
//							SpriteInfo spriteInfo = getSpriteInfo2 (sprite, info.getScale(), oldSprite);
//
//							spriteMap.Add (sprite.name, spriteInfo);
//							if (tex == null)
//							{
//								tex = sprite.texture;
//								pixelsPerUnit = sprite.pixelsPerUnit * info.getScale();
//							}
//						}
//					}
//
//					Debug.Log("createingSpriteSheetConfig_2: " + path);
//
//					string texPath = AssetDatabase.GetAssetPath (tex);
//
//					tex = null;
//					texPath = texPath.Replace (srcPath + "/", "");
//					texPath = texPath.Replace (exts[m], "");
////					texPath = texPath.Replace(EditorSwitchConfig.getSheetDirName(target) + "/", ResourcesEx.SpriteDirName + "/");
//					SpriteSheetLoader loader = new SpriteSheetLoader (texPath, pixelsPerUnit, spriteMap);
//
//					{
//						MemoryStream stream = new MemoryStream ();
//						BinaryWriter writer = new BinaryWriter (stream);
//						loader.Write (writer);
//						string configPath = path.Replace (exts[m], ResourcesEx.spriteSheetConfigSuffix + ".bytes");
//						byte[] bytes = stream.ToArray ();
//						CommonUtil.bytesToFile (configPath, bytes);
//					}
////					{
////						StringWriter writer = new StringWriter ();
////						loader.Write (writer);
////						string configPath = path.Replace (exts[m], ResourcesEx.spriteSheetConfigSuffix + "_test.bytes");
////						string bytes = writer.GetStringBuilder().ToString();
////						File.WriteAllText (configPath, bytes);
////					}
//
//					int i = 0;
//					Debug.Log("createingSpriteSheetConfig_3: " + path);
//					AsyncOperation operation = Resources.UnloadUnusedAssets();
//					while(!operation.isDone && i < 100)
//					{
//						Debug.Log("createingSpriteSheetConfig_3_2: " + operation.progress);
//						yield return new WaitForEndOfFrame();
//						i++;
//					}
//					Debug.Log("createingSpriteSheetConfig_3_5: " + path);
//				}
//			}
//		}
//
//		Debug.Log("createingSpriteSheetConfig_5: ");
//		callBack();
//	}

    public static void CreateSpriteSheetConfig3(string resPath, BuildTarget target, HashSet<string> hashSet = null)
    {
        createSpriteSheetConfig3 (resPath, target, resPath + "/" + EditorCommonTool.getSheetDirName(target), hashSet);
    }

	public static void createSpriteSheetConfig3 (string srcPath, BuildTarget target, string outputPath, HashSet<string> hashSet)
	{
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(srcPath, target.getPlatform());
		for (int m = 0; m < exts.Length; m++)
		{
			string[] paths = Directory.GetFiles (outputPath, "*" + exts[m], SearchOption.AllDirectories);
			foreach (string path in paths)
			{
				if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
				{
					string spriteSheetName = getSpriteSheetNameBySpriteSheetPath(path);
					if(hashSet != null)
					{
						if(!hashSet.Contains(spriteSheetName))
						{
							continue;
						}
					}

					SpriteSheetInfo info = null;
					config.TryGetValue(spriteSheetName, out info);

					
					string ext = Path.GetExtension(path);
					
					Object[] objs = AssetDatabase.LoadAllAssetsAtPath (path);
					Dictionary<string, SpriteInfo> spriteMap = new Dictionary<string, SpriteInfo> ();
					Texture2D tex = null;
					float pixelsPerUnit = 100;
					for (int k = 0; k < objs.Length; k++)
					{
						if (objs [k] is Sprite)
						{
							Sprite sprite = objs [k] as Sprite;

							string oldSpritePath = sprite.name.Replace(ResourcesEx.dirSymbol, '/');
							oldSpritePath = srcPath + "/" + oldSpritePath;
							
							Sprite oldSprite = AssetDatabase.LoadAssetAtPath(oldSpritePath + ext, typeof(Sprite)) as Sprite;

							if(oldSprite == null)
							{
								string realTexPath = Path.GetDirectoryName(oldSpritePath) + ext;
								string realSpriteName = Path.GetFileName(oldSpritePath);
								Object[] objs2 = AssetDatabase.LoadAllAssetsAtPath(realTexPath);
								for(int i = 0; i < objs2.Length; i++)
								{
									if(objs2[i] is Sprite)
									{
										if(objs2[i].name == realSpriteName)
										{
											oldSprite = objs2[i] as Sprite;
											break;
										}
									}
								}
							}

							SpriteInfo spriteInfo = getSpriteInfo2 (sprite, info.getScale(), oldSprite);
							
							spriteMap.Add (sprite.name, spriteInfo);
							if (tex == null)
							{
								tex = sprite.texture;
								pixelsPerUnit = sprite.pixelsPerUnit * info.getScale();
							}
						}
					}
					
					string texPath = AssetDatabase.GetAssetPath (tex);
					Resources.UnloadAsset(tex);

					tex = null;
					texPath = texPath.Replace (srcPath + "/", "");
					texPath = texPath.Replace (exts[m], "");
//					texPath = texPath.Replace(EditorSwitchConfig.getSheetDirName(target) + "/", ResourcesEx.SpriteDirName + "/");
					SpriteSheetLoader loader = new SpriteSheetLoader (texPath, pixelsPerUnit, spriteMap);
					
					{
						MemoryStream stream = new MemoryStream ();
						BinaryWriter writer = new BinaryWriter (stream);
						loader.Write (writer);
						string configPath = path.Replace (exts[m], ResourcesEx.spriteSheetConfigSuffix + ".bytes");
						byte[] bytes = stream.ToArray ();
						CommonUtil.bytesToFile (configPath, bytes);
					}
//					{
//						StringWriter writer = new StringWriter ();
//						loader.Write (writer);
//						string configPath = path.Replace (exts[m], ResourcesEx.spriteSheetConfigSuffix + "_test.bytes");
//						string bytes = writer.GetStringBuilder().ToString();
//						File.WriteAllText (configPath, bytes);
//					}
					
//					int i = 0;
//					Debug.Log("createingSpriteSheetConfig_3: " + path);
//					AsyncOperation operation = Resources.UnloadUnusedAssets();
//					while(!operation.isDone && i < 100)
//					{
//						Debug.Log("createingSpriteSheetConfig_3_2: " + operation.progress);
//						yield return new WaitForEndOfFrame();
//						i++;
//					}
//					Debug.Log("createingSpriteSheetConfig_3_5: " + path);
				}
			}
		}
		
		Debug.Log("createingSpriteSheetConfig_5: ");
	}

    public static void CreateSpriteSheetLoaderScript(string resPath, BuildTarget target, HashSet<string> hashSet = null)
    {
        createSpriteSheetLoaderScript (resPath, target, resPath + "/" + EditorCommonTool.getSheetDirName(target), hashSet);
    }

    public static void createSpriteSheetLoaderScript (string srcPath, BuildTarget target, string outputPath, HashSet<string> hashSet)
    {
        SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(srcPath, target.getPlatform());
        for (int m = 0; m < exts.Length; m++)
        {
            string[] paths = Directory.GetFiles (outputPath, "*" + exts[m], SearchOption.AllDirectories);
            foreach (string path in paths)
            {
                if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
                {
                    string spriteSheetName = getSpriteSheetNameBySpriteSheetPath(path);
                    if(hashSet != null)
                    {
                        if(!hashSet.Contains(spriteSheetName))
                        {
                            continue;
                        }
                    }

                    Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D> (path);
                    Texture2D texAlpha = AssetDatabase.LoadAssetAtPath<Texture2D>(CommonUtil.addSuffixToFileName(path, "_alpha"));
                    Material matSprite = AssetDatabase.LoadAssetAtPath<Material>(System.IO.Path.ChangeExtension(CommonUtil.addSuffixToFileName(path, "_sprite"), ".mat"));
                    Material matUI = AssetDatabase.LoadAssetAtPath<Material>(System.IO.Path.ChangeExtension(CommonUtil.addSuffixToFileName(path, "_ui"), ".mat"));
                    TextAsset texConfig = AssetDatabase.LoadAssetAtPath<TextAsset>(System.IO.Path.ChangeExtension(CommonUtil.addSuffixToFileName(path, "_config"), "bytes"));
                    if (texConfig == null)
                    {
                        Debug.LogError("not found config for sprite sheet: " + path);
                    }

                    Object[] objs = AssetDatabase.LoadAllAssetsAtPath(path);
                    List<Sprite> sprites = new List<Sprite>();
                    for (int i = 0; i < objs.Length; i++)
                    {
                        if (objs[i] is Sprite)
                        {
                            sprites.Add(objs[i] as Sprite);
                        }
                    }
                    SpriteSheetInfoScript loader = new SpriteSheetInfoScript();
                    loader.tex = tex;
                    loader.texAlpha = texAlpha;
                    loader.spriteMat = matSprite;
                    loader.uiMat = matUI;
                    loader.config = texConfig;
                    loader.sprites = sprites.ToArray();
                    AssetDatabase.CreateAsset(loader, System.IO.Path.ChangeExtension(CommonUtil.addSuffixToFileName(path, "_script"), ".asset"));
                }
            }
        }

        Debug.Log("createingSpriteSheetConfig_5: ");
    }

    public static void CreateSpriteToSheetMap(string resPath, BuildTarget target, HashSet<string> hashSet = null)
    {
        createSpriteToSheetMap (resPath, target, resPath + "/" + EditorCommonTool.getSheetDirName(target), hashSet);
    }



    public static void createSpriteToSheetMap (string srcPath, BuildTarget target, string outputPath, HashSet<string> hashSet)
    {
        SpriteToSheetMap result = new SpriteToSheetMap();
        for (int m = 0; m < exts.Length; m++)
        {
            string[] paths = Directory.GetFiles (outputPath, "*" + exts[m], SearchOption.AllDirectories);
            foreach (string path in paths)
            {
                if (!string.IsNullOrEmpty (path) && IsTextureFile (path) && !path.Contains (rgbSuffix) && !path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
                {
                    string configPath = System.IO.Path.ChangeExtension(CommonUtil.addSuffixToFileName(path, "_config"), ".bytes");
                    byte[] data = System.IO.File.ReadAllBytes(configPath);
                    if (data == null)
                    {
                        Debug.LogError("config not found: " + configPath);
                        continue;
                    }
                    SpriteSheetLoader loader = SpriteSheetLoader.CreateFromBinary(data);

                    Dictionary<string, SpriteInfo>.Enumerator en = loader.spriteInfoMap.GetEnumerator();
                    while (en.MoveNext())
                    {
                        string spriteName = en.Current.Key;
                        string key = spriteName.Replace(ResourcesEx.dirSymbol.ToString(), "/");
                        if (result.ContainsKey(key))
                        {
                            throw new System.Exception("repeat tex: " + key);
//                            Debug.LogError("repeat key: " + key);
                        }
                        else
                        {
                            result.Add(key, path.Replace(srcPath + "/", "").Replace(exts[m], "") + "_script");
                        }
                    }
                }
            }
        }

        File.WriteAllBytes(srcPath + "/" + target.ToString() + "/" + "sprite_sheet_map.bytes", result.toBinary());
        string str = JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);
        File.WriteAllText(srcPath + "/" + target.ToString() + "/" + "sprite_sheet_map_json.json", str);
    }

//	[MenuItem("Custom/OldProject/Sprite/CreateSpriteSheetConfig")]
//	public static void CreateSpriteSheetConfig()
//	{
//		CreateSpriteSheetConfig2(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
//	}

//	public static void CreateSpriteSheetConfig2(string resPath, BuildTarget target, HashSet<string> hashSet = null, createSpriteSheetConfigCallBack callBack = null)
//	{
//		EditorCoroutineRunner.StartEditorCoroutine(createSpriteSheetConfig (resPath, target, resPath + "/" + EditorCommonTool.getSheetDirName(target), hashSet, () =>
//		{
//			if(callBack != null)
//			{
//				callBack();
//			}
//		}));
//	}

	public static void MergeAlpha(string resPath, BuildTarget target, HashSet<string> hashSet = null)
	{
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, EditorCommonTool.getPlatform(target));
		string androidSpriteSheetDir = resPath + "/" + EditorCommonTool.getSheetDirName(target);
		
		string[] dirPaths = Directory.GetDirectories (androidSpriteSheetDir, "*", SearchOption.TopDirectoryOnly);
		for(int u = 0; u < dirPaths.Length; u++)
		{
			string dirPath = dirPaths[u];
			string spriteSheetName = Path.GetFileName(dirPath);
			
			if(hashSet != null)
			{
				if(!hashSet.Contains(spriteSheetName))
				{
					continue;
				}
			}
			
			SpriteSheetInfo info = null;
			config.TryGetValue(spriteSheetName, out info);
			if(info.split_alpha_type != SplitAlphaType.NONE)
			{
				string texPath = dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ".png";
				Texture2D tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;
				if(tex.width != tex.height)
				{
					Dictionary<string, TempTextureFormat> dic = SetTextureReadable(texPath);
					int tw =  tex.width;
					int th =  tex.height;
					int w = Mathf.Max(tex.width, tex.height);

					Color[] data = tex.GetPixels();
					Resources.UnloadAsset(tex);
					ReverseTextureReadable(texPath, dic);

					string alphaTexPath = dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.SpriteSheetAlphaSuffix + ".png";
					SetTextureReadable(alphaTexPath);
					Texture2D alphaTex = AssetDatabase.LoadAssetAtPath(alphaTexPath, typeof(Texture2D)) as Texture2D;
					Color[] data2 = alphaTex.GetPixels();
					Resources.UnloadAsset(alphaTex);

					Texture2D newTex = new Texture2D(w, w, TextureFormat.RGB24, false);
					newTex.SetPixels(0, 0, tw, th, data);
					bool horizontal = tw < th;
					if(horizontal)
					{
						newTex.SetPixels(w / 2, 0, tw, th, data2);
					}
					else
					{
						newTex.SetPixels(0, w / 2, tw, th, data2);
					}



					byte[] newData = newTex.EncodeToPNG();
					CommonUtil.bytesToFile(texPath, newData);

					GameObject.DestroyImmediate(newTex);

					CommonUtil.Delete(alphaTexPath);

					{
						Shader shader = Shader.Find("custom/splitalpha2/sprite");
						Material material = new Material (shader);
						material.SetFloat("_Horizontal", horizontal? 1: 0);
						string materialFilePath = dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetMaterialSuffix + ".mat";
						AssetDatabase.CreateAsset (material, materialFilePath);
					}
					{
						Shader shader = Shader.Find("custom/splitalpha2/ui");
						Material material = new Material (shader);
						material.SetFloat("_Horizontal", horizontal? 1: 0);
						string materialFilePath = dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat";
						AssetDatabase.CreateAsset (material, materialFilePath);
					}

					info.split_alpha_type = horizontal? SplitAlphaType.HORIZONTAL: SplitAlphaType.VERTICAL;

//					File.Delete(dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetMaterialSuffix + ".mat");
//					File.Delete(dirPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat");
//					File.WriteAllText(dirPath + "/" + BundleManager.dependenceName + ".bytes", "");
				}
				else
				{
					info.split_alpha_type = SplitAlphaType.SPLIT_TEX;
				}
			}
		}

		EditorCommonTool.setSpriteSheetConfig(config, resPath, EditorCommonTool.getPlatform(target));

		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}

	[MenuItem("Custom/OldProject/Sprite/Seperate RGB and Alpha Channel for All Textures")]
	public static void SeperateAllTexturesRgbAndAlpha()
	{
		SeperateAllTexturesRgbAndAlpha2(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
	}

	public static void SeperateAllTexturesRgbAndAlpha2(string resPath, BuildTarget target, HashSet<string> hashSet = null)
	{
		bool isDel = true;
		Platform p = EditorCommonTool.getPlatform(target);
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, p);
		string androidSpriteSheetDir = resPath + "/" + EditorCommonTool.getSheetDirName(p);

		string[] dirPaths = Directory.GetDirectories (androidSpriteSheetDir, "*", SearchOption.TopDirectoryOnly);
		for(int u = 0; u < dirPaths.Length; u++)
		{
			string dirPath = dirPaths[u];
			string spriteSheetName = Path.GetFileName(dirPath);
			
			if(hashSet != null)
			{
				if(!hashSet.Contains(spriteSheetName))
				{
					continue;
				}
			}

			SpriteSheetInfo info = null;
			config.TryGetValue(spriteSheetName, out info);
			if(info.split_alpha_type != SplitAlphaType.NONE)
			{
				SeparateAlpha (dirPath, isDel);
			}
		}
		AssetDatabase.Refresh();
	}

	static void changeSpriteSheetSpriteTypeToMulti (string resPath, BuildTarget target, string srcPath, HashSet<string> hashSet = null)
	{
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, target.getPlatform());

		for (int m = 0; m < exts.Length; m++)
		{
			string[] paths = Directory.GetFiles (srcPath, "*" + exts[m], SearchOption.AllDirectories);
			for (int i = 0; i < paths.Length; i++)
			{
                string path = paths[i];
                if (!paths[i].Contains(ResourcesEx.SpriteSheetAlphaSuffix))
                {
                    string pathToData = path.Replace(rgbSuffix, "");
                    string ext = Path.GetExtension(pathToData);
                    pathToData = pathToData.Replace(ext, "");

                    string spriteSheetName = getSpriteSheetNameBySpriteSheetPath(pathToData);
                    if (hashSet != null)
                    {
                        if (!hashSet.Contains(spriteSheetName))
                        {
                            continue;
                        }
                    }

                    SpriteSheetInfo info = null;
                    config.TryGetValue(spriteSheetName, out info);

                    TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                    TexturePackerImporter.updateSpriteMetaData(textureImporter, pathToData, resPath, exts[m], info.getScale());
                    AssetDatabase.ImportAsset(path);
                }
                else
                {
                    TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                    textureImporter.setEvonyAttributes();
                    AssetDatabase.ImportAsset(path);
                }
			}
		}
	}

	public static string getSpriteSheetNameBySpriteSheetPath(string spriteSheetPath)
	{
		string spriteSheetName = Path.GetFileNameWithoutExtension (spriteSheetPath);
		int index = spriteSheetName.LastIndexOf(ResourcesEx.SpriteSheetTexSuffix);
		spriteSheetName = spriteSheetName.Remove(index, ResourcesEx.SpriteSheetTexSuffix.Length);
		return spriteSheetName;
	}

	[MenuItem("Custom/OldProject/Sprite/ChangeSpriteSheetToMultiSprite")]
	public static void ChangeSpriteSheetSpriteTypeToMulti()
	{
		ChangeSpriteSheetSpriteTypeToMulti2(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
	}

	public static void ChangeSpriteSheetSpriteTypeToMulti2(string resPath, BuildTarget target, HashSet<string> hashSet = null)
	{
		string srcDir = resPath + "/" + EditorCommonTool.getSheetDirName(target);
		changeSpriteSheetSpriteTypeToMulti (resPath, target, srcDir, hashSet);
		AssetDatabase.Refresh();
	}

	private static void getTextImporters(string srcPath, string ext, ref Dictionary<string, TextureImporter> importerMap)
	{
		string realExt = Path.GetExtension(ext);
		string[] srcTexPaths = Directory.GetFiles(srcPath, ext, SearchOption.AllDirectories);
		for(int i = 0; i < srcTexPaths.Length; i++)
		{
			TextureImporter importer = TextureImporter.GetAtPath(srcTexPaths[i]) as TextureImporter;
//			string key = srcTexPaths[i].Replace(srcPath + "/", "");
			string key = srcTexPaths[i];
			key = key.Replace(realExt, "");

			try
			{
				importerMap.Add(key, importer);
			}
			catch(System.ArgumentException e)
			{
				Debug.Log(e.Message);
			}
		}
	}

	public static string toLocalPath(string path)
	{
		int strIndex = path.IndexOf("Assets/");
		path = path.Substring(strIndex);
		return path;
	}

	static void GetMaterialShader (bool isUI, ref Shader shader)
	{
		if (compress) {
			if (isolation) {
				if (isUI) {
					shader = Shader.Find ("Custom/Android/AlphaCompress/Isolation/UI");
				}
				else {
					shader = Shader.Find ("Custom/Android/AlphaCompress/Isolation/Sprite");
				}
			}
			else {
				if (isUI) {
					shader = Shader.Find ("Custom/Android/AlphaCompress/UI");
				}
				else {
					shader = Shader.Find ("Custom/Android/AlphaCompress/Sprite");
				}
			}
		}
		else {
			if (isUI) {
				shader = Shader.Find ("custom/splitalpha/ui");
			}
			else {
				shader = Shader.Find ("custom/splitalpha/sprite");
			}
		}
	}

	static void createSpriteMaterial (string resPath, BuildTarget target, string outputPath, HashSet<string> hashSet = null)
	{
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath, target.getPlatform());

		string[] paths = Directory.GetFiles (outputPath, "*.png", SearchOption.AllDirectories);
		for (int i = 0; i < paths.Length; i++)
		{
			string path = paths [i];
			if (!path.Contains (ResourcesEx.SpriteSheetAlphaSuffix))
			{
				string spriteSheetName = getSpriteSheetNameBySpriteSheetPath(path);

				if(hashSet != null)
				{
					if(!hashSet.Contains(spriteSheetName))
					{
						continue;
					}
				}

				SpriteSheetInfo createSpriteSheetInfo = null;
				if(!spriteSheetConfig.TryGetValue(spriteSheetName, out createSpriteSheetInfo))
				{
					continue;
				}

				Texture2D rgbTex = AssetDatabase.LoadAssetAtPath (path, typeof(Texture2D)) as Texture2D;
				string alphaFilePath = GetAlphaTexPath (path);
				Texture2D alphaTex = AssetDatabase.LoadAssetAtPath (alphaFilePath, typeof(Texture2D)) as Texture2D;
				if (alphaTex != null)
				{
					bool[] isUiArray = new bool[]{true, false};
					string[] materialSuffix = new string[]{ResourcesEx.spriteSheetUiMaterialSuffix, ResourcesEx.spriteSheetMaterialSuffix};
					for(int k = 0; k < isUiArray.Length; k++)
					{
						Shader shader = null;
						GetMaterialShader (isUiArray[k], ref shader);
						Material material = new Material (shader);
						material.SetInt ("_MainTexWidth", rgbTex.width);
						material.SetInt ("_MaskTexWidth", alphaTex.width);
						if (isolation)
						{
							int alphaWidth = calIsolationWidth (rgbTex.width);
							material.SetInt ("_MaskIsolationWidth", alphaWidth);
						}
						material.SetTexture ("_MaskTex", alphaTex);
                        outputPath = Path.GetDirectoryName(path);
                        string materialFilePath = outputPath + "/" + Path.GetFileNameWithoutExtension (path).Replace (rgbSuffix, "") + materialSuffix[k];
                        AssetDatabase.CreateAsset (material, materialFilePath + ".mat");
					}
				}

				if(rgbTex != null)
				{
					Resources.UnloadAsset(rgbTex);
				}

				if(alphaTex != null)
				{
					Resources.UnloadAsset(alphaTex);
				}
			}
		}
	}
	
	[MenuItem("Custom/OldProject/Sprite/CreateAllSpriteSheetMaterial")]
	public static void CreateSpriteSheetMaterial()
	{
        CreateSpriteSheetMaterial3(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
	}

	public static void CreateSpriteSheetMaterial3(string resPath, BuildTarget target, HashSet<string> hashSet = null)
	{
		Platform p = EditorCommonTool.getPlatform(target);
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, p);
		string androidSpriteSheetDir = resPath + "/" + EditorCommonTool.getSheetDirName(p);
		string[] dirPaths = Directory.GetDirectories (androidSpriteSheetDir, "*", SearchOption.TopDirectoryOnly);
		for(int u = 0; u < dirPaths.Length; u++)
		{
			string dirPath = dirPaths[u];
			string spriteSheetName = Path.GetFileName(dirPath);
			
			if(hashSet != null)
			{
				if(!hashSet.Contains(spriteSheetName))
				{
					continue;
				}
			}

			SpriteSheetInfo info = null;
			config.TryGetValue(spriteSheetName, out info);

			if(info.split_alpha_type != SplitAlphaType.NONE)
			{
				createSpriteMaterial (resPath, target, dirPath, hashSet);
			}
		}
		AssetDatabase.Refresh();
	}

//	private static bool parsePath(string path, string srcPath, ref string spritePath, ref string spriteSheetName, ref string spriteName)
//	{
//		if(!path.StartsWith(srcPath))
//		{
//			return false;
//		}
//
//		spritePath = path.Replace(srcPath + "/", "");
//		
//		spriteSheetName = "";
//		spriteName = "";
//		
//		ResourcesEx.parseSpritePath(spritePath, ref spriteSheetName, ref spriteName, true);
//		return true;
//	}

//	private static Sprite getSprite(ref Dictionary<string, Dictionary<string, Sprite>> spriteSheetMap, Sprite sprite, ref string spriteSheetPath)
//	{
//		string spritePath = AssetDatabase.GetAssetPath(sprite);
//		
//		for(int k = 0; k < TexturePackerImporter.spriteSheetInfos.Length; k++)
//		{
//			SpriteSheetInfo2 info = TexturePackerImporter.spriteSheetInfos[k];
//			string srcPath = info.getSrcPath();
//			if(spritePath.StartsWith(srcPath))
//			{
//				string tempPath = "";
//				string spriteSheetName = "";
//				string spriteName = "";
//
//				parsePath(spritePath, srcPath, ref tempPath, ref spriteSheetName, ref spriteName);
//
//				if(spriteSheetName == "")
//				{
//					Debug.Log("");
//				}
//
//				spriteSheetPath = info.getOutputPath() + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix;
//				string ext = Path.GetExtension(tempPath);
//				
//				Dictionary<string, Sprite> spriteMap = null;
//				if(!spriteSheetMap.TryGetValue(spriteSheetPath, out spriteMap))
//				{
//					spriteMap = new Dictionary<string, Sprite>();
//					Object[] objs = AssetDatabase.LoadAllAssetsAtPath(spriteSheetPath + ext);
//					
//					for(int m = 0; m < objs.Length; m++)
//					{
//						if(objs[m] is Sprite)
//						{
//							spriteMap.Add(objs[m].name, objs[m] as Sprite);
//						}
//					}
//					spriteSheetMap.Add(spriteSheetPath, spriteMap);
//				}
//
//				spriteName = spriteName.Replace('/', ResourcesEx.dirSymbol);
//				spriteName = spriteName.Replace(ext, "");
//				
//				Sprite tempSprite = null;
//				spriteMap.TryGetValue(spriteName, out tempSprite);
//				if(tempSprite != null)
//				{
//					return tempSprite;
//				}
//			}
//		}
//		return null;
//	}

	private static Sprite getSprite(string resPath, ref Dictionary<string, Dictionary<string, Sprite>> spriteSheetMap, string spriteSheetName, string spritePath, string spriteName, ref string spriteSheetPath, BuildTarget target)
	{
		if(spriteSheetName == null)
		{
			return null;
		}

		if(spriteSheetName == "")
		{
			Debug.Log("");
		}

//		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, target.getPlatform());
//		Dictionary<string, SpriteSheetInfo> dic = config.getSpriteSheetGroup(spriteSheetName);
//		Dictionary<string, SpriteSheetInfo>.Enumerator e = dic.GetEnumerator();
//		while(e.MoveNext())
//		{
//			if(e.Current.Value.is_sub_pack)
//			{
//
//			}
//		}
		spriteSheetPath = resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix;
		string ext = Path.GetExtension(spritePath);
		
		Dictionary<string, Sprite> spriteMap = null;
		if(!spriteSheetMap.TryGetValue(spriteSheetPath, out spriteMap))
		{
			spriteMap = new Dictionary<string, Sprite>();
			Object[] objs = AssetDatabase.LoadAllAssetsAtPath(spriteSheetPath + ext);
			
			for(int m = 0; m < objs.Length; m++)
			{
				if(objs[m] is Sprite)
				{
					spriteMap.Add(objs[m].name, objs[m] as Sprite);
				}
			}

			if(spriteMap.Count <= 0)
			{
				Debug.LogError("not found sprites in sprite sheet: " + spriteSheetPath + ext + ", when get sprite " + spritePath);
				spriteSheetMap.Add(spriteSheetPath, null);
			}
			else
			{
				spriteSheetMap.Add(spriteSheetPath, spriteMap);
			}

		}
		
		spritePath = spritePath.Replace('/', ResourcesEx.dirSymbol);
		spritePath = spritePath.Replace(ext, "");

		if(spriteMap == null)
		{
			return null;
		}

		Sprite tempSprite = null;
		spriteMap.TryGetValue(spritePath, out tempSprite);
		if(tempSprite != null)
		{
			return tempSprite;
		}

		spritePath = spritePath + ResourcesEx.dirSymbol + spriteName;
		spriteMap.TryGetValue(spritePath, out tempSprite);
		if(tempSprite != null)
		{
			return tempSprite;
		}

		return null;
	}

	private static RuntimeAnimatorController getAnimatorController(string controllerPath)
	{
		string spriteSheetAnimControllerPath = controllerPath.Replace("/" + ResourcesEx.AnimDirName + "/", "/" + EditorCommonTool.getSheetAnimDirName(EditorUserBuildSettings.activeBuildTarget) + "/");

		RuntimeAnimatorController tempController = null;
		tempController = AssetDatabase.LoadAssetAtPath(spriteSheetAnimControllerPath, typeof(RuntimeAnimatorController)) as RuntimeAnimatorController;
		return tempController;
	}

	private static AnimationClip getAnimationClip(string controllerPath)
	{
		string spriteSheetAnimControllerPath = controllerPath.Replace("/" + ResourcesEx.AnimDirName + "/", "/" + EditorCommonTool.getSheetAnimDirName(EditorUserBuildSettings.activeBuildTarget) + "/");
		
		AnimationClip tempController = null;
		tempController = AssetDatabase.LoadAssetAtPath(spriteSheetAnimControllerPath, typeof(AnimationClip)) as AnimationClip;
		return tempController;
	}

	private static Font getFont(Font font)
	{
		if(font == null)
		{
			return null;
		}

		if(font.material == null)
		{
			return null;
		}

		string path = AssetDatabase.GetAssetPath(font);
        string newPath = path.Replace(ConfigTool.bundleDir[0], ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getPlatform().ToString());
		
		Font newFont = null;
		newFont = AssetDatabase.LoadAssetAtPath(newPath, typeof(Font)) as Font;
		return newFont;
	}

//	private static bool setEmoji(ref UIEmojiImage image)
//	{
//		if(image == null)
//		{
//			return false;
//		}
//		
//		string spritePath = AssetDatabase.GetAssetPath(image.sprite);
//		string newSpritePath = spritePath.Replace(CreateSpriteSheet.bundleDir, ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getPlatform().ToString());
//		Sprite newSprite = null;
//		newSprite = AssetDatabase.LoadAssetAtPath(newSpritePath, typeof(Sprite)) as Sprite;
//		image.sprite = newSprite;
//
//
//		string materialPath = AssetDatabase.GetAssetPath(image.material);
//		string newMaterialPath = materialPath.Replace(CreateSpriteSheet.bundleDir, ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getPlatform().ToString());
//		Material newMat = null;
//		newMat = AssetDatabase.LoadAssetAtPath(newMaterialPath, typeof(Material)) as Material;
//		image.material = newMat;
//		return true;
//	}

	private static Font getRawFont(Font font)
	{
		if(font == null)
		{
			return null;
		}
		
		if(font.material == null)
		{
			return null;
		}
		
		string path = AssetDatabase.GetAssetPath(font);
		string newPath = path.Replace(ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getPlatform().ToString(), ConfigTool.bundleDir[0]);
		
		Font newFont = null;
		newFont = AssetDatabase.LoadAssetAtPath(newPath, typeof(Font)) as Font;
		return newFont;
	}

	static Sprite getRawSprite(Sprite sprite)
	{
		string path = AssetDatabase.GetAssetPath(sprite);
		if(path.Contains("/" + ResourcesEx.SheetDirName + "/"))
		{
			string rawPath = sprite.name.Replace(ResourcesEx.dirSymbol, '/');
			rawPath = ConfigTool.bundleDir[0] + "/" + rawPath;
			string ext = Path.GetExtension(path);
			return AssetDatabase.LoadAssetAtPath(rawPath + ext, typeof(Sprite)) as Sprite;
		}
		return null;
	}

	static RuntimeAnimatorController getRawAnimatorController(RuntimeAnimatorController controller)
	{
		string controllerPath = AssetDatabase.GetAssetPath(controller);
		string animPath = "/" + EditorCommonTool.getSheetAnimDirName(BuildTarget.Android) + "/";
		string rawAnimPath = "/" + ResourcesEx.AnimDirName + "/";
		if(controllerPath.Contains(animPath))
		{
			controllerPath =controllerPath.Replace(animPath, rawAnimPath);
			return AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController)) as RuntimeAnimatorController;
		}
		else
		{
			animPath = "/" + EditorCommonTool.getSheetAnimDirName(EditorCommonTool.build_target_ios) + "/";
			if(controllerPath.Contains(animPath))
			{
				controllerPath =controllerPath.Replace(animPath, rawAnimPath);
				return AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController)) as RuntimeAnimatorController;
			}
		}
		return null;
	}

	static AnimationClip getRawAnimationClip(AnimationClip controller)
	{
		string controllerPath = AssetDatabase.GetAssetPath(controller);
		string animPath = "/" + EditorCommonTool.getSheetAnimDirName(BuildTarget.Android) + "/";
		string rawAnimPath = "/" + ResourcesEx.AnimDirName + "/";
		if(controllerPath.Contains(animPath))
		{
			controllerPath =controllerPath.Replace(animPath, rawAnimPath);
			return AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimationClip)) as AnimationClip;
		}
		else
		{
			animPath = "/" + EditorCommonTool.getSheetAnimDirName(EditorCommonTool.build_target_ios) + "/";
			if(controllerPath.Contains(animPath))
			{
				controllerPath =controllerPath.Replace(animPath, rawAnimPath);
				return AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimationClip)) as AnimationClip;
			}
		}
		return null;
	}

	[MenuItem("Custom/OldProject/Prefab/RevertPrefab")]
	public static void RevertPrefab()
	{
		GameObject obj = new GameObject();
		SpriteRenderer defaultRender = obj.AddComponent<SpriteRenderer>();
		Material defaultMaterial = defaultRender.sharedMaterial;
		GameObject.DestroyImmediate(obj);

		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				bool isNeedSave = false;
				Object realPrefab = AssetDatabase.LoadAssetAtPath(paths[i], typeof(Object));
				GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;

				SpriteRenderer[] renders = prefab.GetComponentsInChildren<SpriteRenderer>(true);
				for(int j = 0; j < renders.Length; j++)
				{
					SpriteRenderer render = renders[j];
					Sprite sprite = render.sprite;
					if(sprite != null)
					{
						Sprite tempSprite = getRawSprite(sprite);
						if(tempSprite != null)
						{
							render.sprite = tempSprite;
							render.sharedMaterial = defaultMaterial;
							isNeedSave = true;
						}
					}
				}
				
				Image[] images = prefab.GetComponentsInChildren<Image>(true);
				for(int j = 0; j < images.Length; j++)
				{
					Image image = images[j];
					Sprite sprite = image.sprite;
					if(sprite != null)
					{
						Sprite tempSprite = getRawSprite(sprite);
						if(tempSprite != null)
						{
							image.sprite = tempSprite;
							image.material = null;
							isNeedSave = true;
						}
					}
				}

				Button[] buttons = prefab.GetComponentsInChildren<Button>(true);
				for(int j = 0; j < buttons.Length; j++)
				{
					Button button = buttons[j];
					if(button.transition == Selectable.Transition.SpriteSwap)
					{
						bool settedMaterial = false;
						SpriteState state = button.spriteState;
						Sprite sprite = state.pressedSprite;
						if(sprite != null)
						{
							Sprite tempSprite = getRawSprite(sprite);
							if(tempSprite != null)
							{
								state.pressedSprite = tempSprite;
								button.image.material = null;
								isNeedSave = true;
								settedMaterial = true;
							}
						}
						
						sprite = state.disabledSprite;
						if(sprite != null)
						{
							Sprite tempSprite = getRawSprite(sprite);
							if(tempSprite != null)
							{
								state.disabledSprite = tempSprite;
								button.image.material = null;
								isNeedSave = true;
								settedMaterial = true;
							}
						}
						
						sprite = state.highlightedSprite;
						if(sprite != null)
						{
							Sprite tempSprite = getRawSprite(sprite);
							if(tempSprite != null)
							{
								state.highlightedSprite = tempSprite;
								button.image.material = null;
								isNeedSave = true;
								settedMaterial = true;
							}
						}
						
						if(settedMaterial)
						{
							button.spriteState = state;
						}
					}
				}

				Animation[] animations = prefab.GetComponentsInChildren<Animation>(true);
				for(int j = 0; j < animations.Length; j++)
				{
					Animation animation = animations[j];
					AnimationClip clip = animation.clip;
					if(clip != null)
					{
						AnimationClip tempController = getRawAnimationClip(clip);
						if(tempController != null)
						{
							animation.clip = tempController;
							SpriteRenderer render = animation.gameObject.GetComponent<SpriteRenderer>();
							if(render != null && render.sprite == null)
							{
								render.sharedMaterial = defaultMaterial;
							}
							isNeedSave = true;
						}
					}
				}

				Animator[] animators = prefab.GetComponentsInChildren<Animator>(true);
				for(int j = 0; j < animators.Length; j++)
				{
					Animator animator = animators[j];
					RuntimeAnimatorController controller = animator.runtimeAnimatorController;
					if(controller != null)
					{
						RuntimeAnimatorController tempController = getRawAnimatorController(controller);
						if(tempController != null)
						{
							animator.runtimeAnimatorController = tempController;
							SpriteRenderer render = animator.gameObject.GetComponent<SpriteRenderer>();
							if(render != null && render.sprite == null)
							{
								render.sharedMaterial = defaultMaterial;
							}
							isNeedSave = true;
						}
					}
				}

				Text[] texts = prefab.GetComponentsInChildren<Text>(true);
				for(int j = 0; j < texts.Length; j++)
				{
					Text text = texts[j];
					Font font = text.font;
					Font tempFont = getRawFont(font);
					if(tempFont != null)
					{
						text.font = tempFont;
						text.material = tempFont.material;
						
						isNeedSave = true;
					}
				}

				if(isNeedSave)
				{
					PrefabUtility.ReplacePrefab(prefab, realPrefab, ReplacePrefabOptions.ConnectToPrefab);
				}
				
				GameObject.DestroyImmediate(prefab);
			}
		}

		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}
	
	public static HashSet<string> getPrefabSpritePath(string prefabPath, Dictionary<string, string> idMap)
	{
		HashSet<string> texPaths = new HashSet<string>();

		string str = CommonUtil.fileToString(prefabPath);
		if(str == null)
		{
			Debug.LogError("str is null:" + prefabPath);
		}
		string exp2 = @"\{fileID:\s*(\d+),\s*guid:\s*(.+),\s*type:\s*3\}";
		MatchCollection matches = Regex.Matches(str, exp2);

		for(int k = 0; k < matches.Count; k++)
		{
			Match match = matches[k];
//			string spriteFileId = match.Groups[1].Value;
			string texGuid = match.Groups[2].Value;
			
			string info = null;
			if(idMap.TryGetValue(texGuid, out info))
			{
				texPaths.Add(info);
			}
		}

		GameObject obj = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(Object)) as GameObject;
		Animator[] animators = obj.GetComponents<Animator>();
		for(int i = 0; i < animators.Length; i++)
		{
			RuntimeAnimatorController controller = animators[i].runtimeAnimatorController;
			string controllerPath = AssetDatabase.GetAssetPath (controller);
			string[] dependenceFiles = AssetDatabase.GetDependencies(new string[]{controllerPath});
			for(int j = 0; j < dependenceFiles.Length; j++)
			{
				string path = dependenceFiles[j];
				for(int k = 0; k < exts.Length; k++)
				{
					if(path.EndsWith(exts[k]))
					{
						texPaths.Add(path);
					}
				}
			}
		}


		Animation[] animations = obj.GetComponentsInChildren<Animation> (true);
		for (int i = 0; i < animations.Length; i++) {
            Animation animation = animations [i];
            AnimationClip clip = animation.clip;
			string controllerPath = AssetDatabase.GetAssetPath (clip);
			string[] dependenceFiles = AssetDatabase.GetDependencies(new string[]{controllerPath});
			for(int j = 0; j < dependenceFiles.Length; j++)
			{
				string path = dependenceFiles[j];
				for(int k = 0; k < exts.Length; k++)
				{
					if(path.EndsWith(exts[k]))
					{
						texPaths.Add(path);
					}
				}
			}
		}

		return texPaths;

//		string path = prefabPath;
//
//		Object realPrefab = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
//		if(realPrefab == null)
//		{
//			return null;
//		}
//
//		HashSet<string> dePaths = new HashSet<string>();
//		GameObject prefab = realPrefab as GameObject;
//		if(prefab == null)
//		{
//			return null;
//		}
//		SpriteRenderer[] renders = prefab.GetComponentsInChildren<SpriteRenderer>(true);
//		for(int j = 0; j < renders.Length; j++)
//		{
//			SpriteRenderer render = renders[j];
//			Sprite sprite = render.sprite;
//			if(sprite != null)
//			{
//				string spritePath = AssetDatabase.GetAssetPath(sprite);
//				dePaths.Add(spritePath);
//			}
//		}
//		
//		Image[] images = prefab.GetComponentsInChildren<Image>(true);
//		for(int j = 0; j < images.Length; j++)
//		{
//			Image image = images[j];
//			Sprite sprite = image.sprite;
//			if(sprite != null)
//			{
//				string spritePath = AssetDatabase.GetAssetPath(sprite);
//				dePaths.Add(spritePath);
//			}
//		}
//		
//		Button[] buttons = prefab.GetComponentsInChildren<Button>(true);
//		for(int j = 0; j < buttons.Length; j++)
//		{
//			Button button = buttons[j];
//			if(button.transition == Selectable.Transition.SpriteSwap)
//			{
//				bool settedMaterial = false;
//				SpriteState state = button.spriteState;
//				Sprite sprite = state.pressedSprite;
//				if(sprite != null)
//				{
//					string spritePath = AssetDatabase.GetAssetPath(sprite);
//					dePaths.Add(spritePath);
//				}
//				
//				sprite = state.disabledSprite;
//				if(sprite != null)
//				{
//					string spritePath = AssetDatabase.GetAssetPath(sprite);
//					dePaths.Add(spritePath);
//				}
//				
//				sprite = state.highlightedSprite;
//				if(sprite != null)
//				{
//					string spritePath = AssetDatabase.GetAssetPath(sprite);
//					dePaths.Add(spritePath);
//				}
//			}
//		}
//				
//		GameObject.DestroyImmediate(prefab);
//
//		return dePaths;
	}

	[MenuItem("Custom/OldProject/Prefab/CreateAllPrefabPathList")]
	public static void CreateAllPrefabPathList()
	{
		CreatePrefabPathList2("Assets");
	}

	private const string prefabListFileName = "prefab_list.json";
	public static void CreatePrefabPathList2(string resPath)
	{
		string[] paths = Directory.GetFiles(resPath, "*.prefab", SearchOption.AllDirectories);
		string str = JsonConvert.SerializeObject(paths, Newtonsoft.Json.Formatting.Indented);
		CommonUtil.stringToFile(resPath + "/" + prefabListFileName, str);

		AssetDatabase.Refresh();
	}

	public static void DeletePrefabPathList2(string resPath)
	{
		CommonUtil.Delete(resPath + "/" + prefabListFileName);
		
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/Prefab/changeScriptSprite")]
	static void changeScriptSprite2 ()
	{
        Dictionary<KeyValuePair<string, string>, SpriteIdInfo> idMap = getSpriteIdInfoMap(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
        changeScriptSprite2(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget, new string[]{ConfigTool.bundleDir[0]}, idMap);
	}

	class SpriteIdInfo
	{
		public string spritePath;
		public string spriteSheetPath;
		public string texGuid;
		public string spriteFileId;
//		public string spriteMaterialFileId;
//		public string spriteMaterialGuid;
//		public string uiMaterialFileId;
//		public string uiMaterialGuid;
	}

	static string GetMaterialBySpritePath (SpriteSheetConfig config, string resPath, BuildTarget target, string spritePath, bool isUI)
	{
		string newSpriteName = spritePath.Replace (resPath + "/", "");
		string spriteSheetName = config.getSpriteSheetName (newSpriteName);
		string materialPath = resPath + "/" + EditorCommonTool.getSheetDirName (target) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + (isUI? ResourcesEx.spriteSheetUiMaterialSuffix: ResourcesEx.spriteSheetMaterialSuffix) + ".mat";
		return materialPath;
	}

	class ReplaceInfo
	{
		public int index;
		public int len;
		public string str;
		public string fileId;
		public string guid;
		public SpriteIdInfo info;
	}

	static HashSet<string> getDependenceGuids(string path)
	{
		HashSet<string> idMap = new HashSet<string>();
		string exp2 = @"\{fileID:\s*(\d+),\s*guid:\s*(.+),\s*type:\s*3\}";
				
		string str = CommonUtil.fileToString(path);
		MatchCollection matches = Regex.Matches(str, exp2);
		for(int k = 0; k < matches.Count; k++)
		{
			Match match = matches[k];
			string texGuid = match.Groups[2].Value;
			idMap.Add(texGuid);
		}
		
		return idMap;
	}
	
	static Dictionary<string, string> getSpriteIdInfoMap3(string texPath, ref Dictionary<string, string> idMap2, ref string texGuid)
	{
		texGuid = AssetDatabase.AssetPathToGUID(texPath);

		Dictionary<string, string> idMap = new Dictionary<string, string>();

		string exp = @"\s+(\d+):\s*(.*)\s*$";
		string exp3 = @"\s+name:\s*(.*)\s*$";

		string spriteSheetPath = texPath;

		
		string metaFilePath = spriteSheetPath + ".meta";
		string str = CommonUtil.fileToString(metaFilePath);
		if(str == null)
		{
			Debug.LogError("read file failed:" + metaFilePath);
			return null;
		}
		
		HashSet<string> spriteNames = new HashSet<string>();
		StringReader reader2 = new StringReader(str);
		while(true)
		{
			string line = reader2.ReadLine();
			if(string.IsNullOrEmpty(line))
			{
				break;
			}
			
			Match match = Regex.Match(line, exp3);
			if (!match.Success)
			{
				continue;
			}
			
			string spriteName = match.Groups[1].Value;
			spriteNames.Add(spriteName);
		}
		
		string findStr = "fileIDToRecycleName:\n";
		int index = str.IndexOf(findStr);
		
		StringReader reader = new StringReader(str.Substring(index + findStr.Length));
		while(true)
		{
			string line = reader.ReadLine();
			if(string.IsNullOrEmpty(line))
			{
				break;
			}
			
			Match match = Regex.Match(line, exp);
			if (!match.Success)
			{
				break;
			}
			
			string spriteFileId = match.Groups[1].Value;
			string spriteName = match.Groups[2].Value;
			
			if(!spriteNames.Contains(spriteName))
			{
				continue;
			}

			idMap.Add(spriteFileId, spriteName);
			idMap2.Add(spriteName, spriteFileId);
		}

		if(idMap.Count <= 0)
		{
			string spriteName = Path.GetFileNameWithoutExtension(texPath);
			idMap.Add("21300000", spriteName);
			idMap2.Add(spriteName, "21300000");
		}
		return idMap;
	}

	static Dictionary<KeyValuePair<string, string>, SpriteIdInfo> getSpriteIdInfoMap(string resPath, BuildTarget target)
	{
		Dictionary<KeyValuePair<string, string>, SpriteIdInfo> idMap = new Dictionary<KeyValuePair<string, string>, SpriteIdInfo>();
		
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath);

		SpriteSheetConfig.Enumerator enumerator = spriteSheetConfig.GetEnumerator();
		while(enumerator.MoveNext())
		{
			if(!enumerator.Current.Value.isLeaf())
			{
				continue;
			}
			string spriteSheetName = enumerator.Current.Key;
			
			string spriteSheetPath = resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix;

			string ext = ".jpg";
			if(!File.Exists(spriteSheetPath + ext))
			{
				ext = ".png";
			}

			string texGuid = null;

			Dictionary<string, string> idMap2 = new Dictionary<string, string>();
			Dictionary<string, string> idMap3 = getSpriteIdInfoMap3(spriteSheetPath + ext, ref idMap2, ref texGuid);

			Dictionary<string, string>.Enumerator e = idMap3.GetEnumerator();
			while(e.MoveNext())
			{
				string spriteFileId = e.Current.Key;
				string spriteName = e.Current.Value;
				string realSpritePath = resPath + "/" + spriteName.Replace(ResourcesEx.dirSymbol, '/');

				string simpleSpriteFileId = null;
				string spriteTexGuid = null;
				if(!File.Exists(realSpritePath + ext))
				{
					string spriteName2 = Path.GetFileName(realSpritePath);
					string realSpritePath2 = Path.GetDirectoryName(realSpritePath);

					Dictionary<string, string> spriteIdMap = new Dictionary<string, string>();
					getSpriteIdInfoMap3(realSpritePath2 + ext, ref spriteIdMap, ref spriteTexGuid);

					spriteIdMap.TryGetValue(spriteName2, out simpleSpriteFileId);
				}
				else
				{
					simpleSpriteFileId = "21300000";
					spriteTexGuid = AssetDatabase.AssetPathToGUID(realSpritePath + ext);
				}



                if(string.IsNullOrEmpty(spriteTexGuid))
                {
					Debug.LogError("not found simple sprite: " + realSpritePath);
                    continue;
                }
                
                SpriteIdInfo info = new SpriteIdInfo();
                info.texGuid = texGuid;
                info.spriteFileId = spriteFileId;
                info.spritePath = realSpritePath;
                info.spriteSheetPath = spriteSheetPath;
                
                SpriteIdInfo oldInfo = null;
				if(idMap.TryGetValue(new KeyValuePair<string, string>(simpleSpriteFileId, spriteTexGuid), out oldInfo))
                {
                    string s = "sprite repeated_0: " + spriteTexGuid + "\n";
					s += "sprite repeated_1: " + info.spritePath + "\n";
					s += "sprite repeated_2: " + info.spriteSheetPath + "\n";
					s += "sprite repeated_3: " + oldInfo.spritePath + "\n";
					s += "sprite repeated_4: " + info.spriteSheetPath + "\n";
					Debug.LogError(s);
                }
				else
				{
					idMap.Add(new KeyValuePair<string, string>(simpleSpriteFileId, spriteTexGuid), info);
				}
            }
        }

		return idMap;
    }


	static Dictionary<string, string> getAllResGuidMap(string resPath)
	{
		Dictionary<string, string> idMap = new Dictionary<string, string>();
		string[] paths = Directory.GetFiles(resPath, "*.meta", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i].Substring(0, paths[i].Length - 5);
			string guid = AssetDatabase.AssetPathToGUID(path);
			idMap.Add(guid, path);
		}
		return idMap;
	}


	public static Dictionary<string, string> getSpriteIdInfoMap2(string resPath)
	{
		Dictionary<string, string> idMap = new Dictionary<string, string>();
		
		string[] exts = new string[]{".jpg", ".png"};
		for(int j = 0; j < exts.Length; j++)
		{
			string [] files = Directory.GetFiles(resPath + "/Sprite/UI/UIInterface", "*" + exts[j], SearchOption.AllDirectories);
			for(int i = 0; i < files.Length; i++)
			{
				string path = files[i];
				string guid = AssetDatabase.AssetPathToGUID(path);
				idMap.Add(guid, path);
			}
		}
		
		return idMap;
	}
    
	static void changeScriptSprite2 (string resPath, BuildTarget target, string[] dirs, Dictionary<KeyValuePair<string, string>, SpriteIdInfo> idMap)
    {
		string exp2 = @"\{fileID:\s*(\d+),\s*guid:\s*(.+),\s*type:\s*3\}";

		for(int u = 0; u < dirs.Length; u++)
		{
			string dir = dirs[u];

			string[] paths = null;
			if(!string.IsNullOrEmpty(Path.GetExtension(dir)))
			{
				if(!dir.EndsWith(".prefab"))
				{
					continue;
				}
				paths = new string[]{dir};
			}
			else
			{
				paths = Directory.GetFiles(dir, "*.prefab", SearchOption.AllDirectories);
			}

			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths[i];
				string str = CommonUtil.fileToString(path);
				
				MatchCollection matches = Regex.Matches(str, exp2);

				List<ReplaceInfo> replaces = new List<ReplaceInfo>();
				for(int k = 0; k < matches.Count; k++)
				{
					Match match = matches[k];
					string spriteFileId = match.Groups[1].Value;
					string texGuid = match.Groups[2].Value;
					
					SpriteIdInfo info = null;
					if(idMap.TryGetValue(new KeyValuePair<string, string>(spriteFileId, texGuid), out info))
	                {
	                    ReplaceInfo replaceInfo = new ReplaceInfo();
	                    replaceInfo.index = match.Index;
	                    replaceInfo.len = match.Length;
	                    replaceInfo.str = match.Value;
	                    replaceInfo.info = info;
	                    replaceInfo.fileId = spriteFileId;
	                    replaceInfo.guid = texGuid;
	                    replaces.Add(replaceInfo);
	                }
				}

				if(replaces.Count > 0)
				{
					Debug.Log("replace prefab: " + path);
				}

				for(int j = replaces.Count - 1; j >= 0; j--)
				{
					ReplaceInfo replaceInfo = replaces[j];
					if(replaces.Count > 0)
					{
						Debug.Log("replace sprite: " + replaceInfo.guid + " " + replaceInfo.info.texGuid);
					}

					string newStr = replaceInfo.str.Replace(replaceInfo.fileId, replaceInfo.info.spriteFileId);
					newStr = newStr.Replace(replaceInfo.guid, replaceInfo.info.texGuid);
					str = str.Insert(replaceInfo.index + replaceInfo.len, newStr);
					str = str.Remove(replaceInfo.index, replaceInfo.len);
				}

				CommonUtil.stringToFile(path, str);
			}
		}

		AssetDatabase.Refresh();
	}

	static Sprite getClipSprite (AnimationClip clip)
	{
		Sprite sprite = null;
		EditorCurveBinding[] curveBindings = AnimationUtility.GetObjectReferenceCurveBindings (clip);
		for (int j = 0; j < curveBindings.Length; j++)
		{
			if (curveBindings [j].propertyName == "m_Sprite")
			{
				ObjectReferenceKeyframe[] keyFrame = AnimationUtility.GetObjectReferenceCurve (clip, curveBindings [j]);
				for (int k = 0; k < keyFrame.Length; k++)
				{
					sprite = keyFrame [k].value as Sprite;
					if (sprite != null)
					{
						break;
					}
				}
			}
			if (sprite != null)
			{
				break;
			}
		}
		return sprite;
	}

	static void setPrefabReference3 (string resPath, BuildTarget target, string[] paths)
	{
//		Resources.UnloadUnusedAssets();
//		System.GC.Collect();

		
		HashSet<Texture> texSet = new HashSet<Texture>();

		Dictionary<string, Dictionary<string, Sprite>> spriteSheetMap = new Dictionary<string, Dictionary<string, Sprite>>();
		
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath);
		
		for (int i = 0; i < paths.Length; i++)
		{
			string path = paths [i];

			bool isNeedSave = false;

			Object realPrefab = AssetDatabase.LoadAssetAtPath (path, typeof(Object));
			if (realPrefab == null)
			{
				Debug.LogError ("InstantiatePrefab failed: " + path);
				continue;
			}


//			GameObject prefab = PrefabUtility.InstantiatePrefab (realPrefab) as GameObject;
			GameObject prefab = realPrefab as GameObject;
			if (prefab == null)
			{
				Debug.LogError ("InstantiatePrefab failed 2: " + path);
				continue;
			}
			
			SpriteRenderer[] renders = prefab.GetComponentsInChildren<SpriteRenderer> (true);
			for (int j = 0; j < renders.Length; j++)
			{
				SpriteRenderer render = renders [j];
				Sprite sprite = render.sprite;
				if (sprite != null)
				{
					string spritePath = AssetDatabase.GetAssetPath (sprite);

					Material m = render.sharedMaterial;
					string newSpriteName = spritePath.Replace (resPath + "/", "");
					string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
					string spriteSheetPath = "";
					Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
					if (tempSprite != null)
					{
						render.sprite = tempSprite;
						if (m.name == "Sprites-Default")
						{
							Material material = AssetDatabase.LoadAssetAtPath (spriteSheetPath + ResourcesEx.spriteSheetMaterialSuffix + ".mat", typeof(Material)) as Material;
							if (material != null)
							{
								render.sharedMaterial = material;
							}
						}
						isNeedSave = true;
					}
				}
			}
			Image[] images = prefab.GetComponentsInChildren<Image> (true);
			for (int j = 0; j < images.Length; j++) {
				Image image = images [j];
				Sprite sprite = image.sprite;
				if (sprite != null) {
					string spritePath = AssetDatabase.GetAssetPath (sprite);
					string newSpriteName = spritePath.Replace (resPath + "/", "");
					string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
					string spriteSheetPath = "";
					Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
					if (tempSprite != null) {
						image.sprite = tempSprite;
						Material material = AssetDatabase.LoadAssetAtPath (spriteSheetPath + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat", typeof(Material)) as Material;
						if (material != null) {
							image.material = material;
						}
						isNeedSave = true;
					}
				}
			}
			Button[] buttons = prefab.GetComponentsInChildren<Button> (true);
			for (int j = 0; j < buttons.Length; j++) {
				Button button = buttons [j];
				if (button.transition == Selectable.Transition.SpriteSwap) {
					bool settedMaterial = false;
					SpriteState state = button.spriteState;
					Sprite sprite = state.pressedSprite;
					if (sprite != null) {
						string spritePath = AssetDatabase.GetAssetPath (sprite);
						string newSpriteName = spritePath.Replace (resPath + "/", "");
						string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
						string spriteSheetPath = "";
						Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
						if (tempSprite != null) {
							state.pressedSprite = tempSprite;
							Material material = AssetDatabase.LoadAssetAtPath (spriteSheetPath + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat", typeof(Material)) as Material;
							if (material != null) {
								button.image.material = material;
							}
							settedMaterial = true;
							isNeedSave = true;
						}
					}
					sprite = state.disabledSprite;
					if (sprite != null) {
						string spritePath = AssetDatabase.GetAssetPath (sprite);
						string newSpriteName = spritePath.Replace (resPath + "/", "");
						string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
						string spriteSheetPath = "";
						Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
						if (tempSprite != null) {
							state.disabledSprite = tempSprite;
							if (!settedMaterial) {
								Material material = AssetDatabase.LoadAssetAtPath (spriteSheetPath + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat", typeof(Material)) as Material;
								if (material != null) {
									button.image.material = material;
								}
								settedMaterial = true;
							}
							isNeedSave = true;
						}
					}
					sprite = state.highlightedSprite;
					if (sprite != null) {
						string spritePath = AssetDatabase.GetAssetPath (sprite);
						string newSpriteName = spritePath.Replace (resPath + "/", "");
						string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
						string spriteSheetPath = "";
						Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
						if (tempSprite != null) {
							state.highlightedSprite = tempSprite;
							if (!settedMaterial) {
								Material material = AssetDatabase.LoadAssetAtPath (spriteSheetPath + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat", typeof(Material)) as Material;
								if (material != null) {
									button.image.material = material;
								}
								settedMaterial = true;
							}
							isNeedSave = true;
						}
					}
					if (settedMaterial) {
						button.spriteState = state;
					}
				}
			}
//			Animator[] animators = prefab.GetComponentsInChildren<Animator> (true);
//			for (int j = 0; j < animators.Length; j++) {
//				Animator animator = animators [j];
//				RuntimeAnimatorController controller = animator.runtimeAnimatorController;
//				if (controller != null) {
//					string controllerPath = AssetDatabase.GetAssetPath (controller);
//
//					Sprite sprite = null;
//
//					AnimatorController assetController = AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimatorController)) as AnimatorController;
//					AnimatorControllerLayer tempLayer = assetController.GetLayer(0);
//					UnityEditorInternal.StateMachine sm2 = tempLayer.stateMachine;
//					int count = sm2.stateCount;
//					for(int v = 0; v < count; v++)
//					{
//						State state = sm2.GetState(v);
//						Motion motion = state.GetMotion();
//						if(motion is AnimationClip)
//						{
//							AnimationClip clip = motion as AnimationClip;
//							sprite = getClipSprite (clip);
//							if(sprite != null)
//							{
//								break;
//							}
//						}
//					}
//
//					if(sprite != null)
//					{
//						texSet.Add(sprite.texture);
//						string spritePath = AssetDatabase.GetAssetPath(sprite);
//						{
//							Material material = null;
//							SpriteRenderer render = animator.gameObject.GetComponent<SpriteRenderer> ();
//							if (render != null && render.sprite == null)
//							{
//								if(material == null)
//								{
//									string materialPath = GetMaterialBySpritePath (spriteSheetConfig, resPath, target, spritePath, false);
//									material = AssetDatabase.LoadAssetAtPath (materialPath, typeof(Material)) as Material;
//									if(material == null)
//									{
//										break;
//									}
//								}
//								render.sharedMaterial = material;
//								isNeedSave = true;
//							}
//						}
//						{
//							Material material = null;
//							Image image = animator.gameObject.GetComponent<Image> ();
//							if (image != null && image.sprite == null)
//							{
//								if(material == null)
//								{
//									string materialPath = GetMaterialBySpritePath (spriteSheetConfig, resPath, target, spritePath, true);
//									material = AssetDatabase.LoadAssetAtPath (materialPath, typeof(Material)) as Material;
//									if(material == null)
//									{
//										break;
//									}
//								}
//								image.material = material;
//								isNeedSave = true;
//							}
//						}
//					}
//				}
//			}
//			Animation[] animations = prefab.GetComponentsInChildren<Animation> (true);
//            for (int j = 0; j < animations.Length; j++) {
//                Animation animation = animations [j];
//                AnimationClip clip = animation.clip;
//                if (clip != null) {
////                    string controllerPath = AssetDatabase.GetAssetPath (clip);
////                    AnimationClip tempController = getAnimationClip (controllerPath);
////                    if (tempController != null) {
//						//for test build bundle
////                        animation.clip = tempController;
//					Sprite sprite = getClipSprite (clip);
//					if(sprite != null)
//					{
//						texSet.Add(sprite.texture);
//						string spritePath = AssetDatabase.GetAssetPath(sprite);
//						{
//
//							Material material = null;
//							SpriteRenderer render = animation.gameObject.GetComponent<SpriteRenderer> ();
//							if (render != null && render.sprite == null)
//							{
//								if(material == null)
//								{
//									string materialPath = GetMaterialBySpritePath (spriteSheetConfig, resPath, target, spritePath, false);
//									material = AssetDatabase.LoadAssetAtPath (materialPath, typeof(Material)) as Material;
//									if(material == null)
//									{
//										break;
//									}
//								}
//								render.sharedMaterial = material;
//								isNeedSave = true;
//							}
//						}
//						{
//							
//							Material material = null;
//							Image image = animation.gameObject.GetComponent<Image> ();
//							if (image != null && image.sprite == null)
//							{
//								if(material == null)
//								{
//									string materialPath = GetMaterialBySpritePath (spriteSheetConfig, resPath, target, spritePath, true);
//									material = AssetDatabase.LoadAssetAtPath (materialPath, typeof(Material)) as Material;
//									if(material == null)
//									{
//										break;
//									}
//								}
//								image.material = material;
//								isNeedSave = true;
//							}
//						}
//					}
//                }
//            }
//            Text[] texts = prefab.GetComponentsInChildren<Text> (true);
//            for (int j = 0; j < texts.Length; j++) {
//                Text text = texts [j];
//                Font font = text.font;
//                Font tempFont = getFont (font);
//                if (tempFont != null) {
//                    text.font = tempFont;
//                    text.material = tempFont.material;
//                    isNeedSave = true;
//                }
//            }
//            UIEmojiImage[] emojiImage = prefab.GetComponentsInChildren<UIEmojiImage> (true);
//            for (int j = 0; j < emojiImage.Length; j++) {
//                UIEmojiImage image = emojiImage [j];
//                if (setEmoji (ref image)) {
//                    isNeedSave = true;
//                }
//            }

//            if (isNeedSave) {
//                try {
//                    PrefabUtility.ReplacePrefab (prefab, realPrefab, ReplacePrefabOptions.ConnectToPrefab);
//                }
//                catch (System.Exception e) {
//                    Debug.LogException (e);
//                }
//            }	
//            GameObject.DestroyImmediate (prefab);
			if(isNeedSave)
			{
				EditorUtility.SetDirty(prefab);
			}
		}

		Dictionary<string, Dictionary<string, Sprite>>.Enumerator e = spriteSheetMap.GetEnumerator();
		while(e.MoveNext())
		{
			Dictionary<string, Sprite>.Enumerator e2 = e.Current.Value.GetEnumerator();
			while(e2.MoveNext())
			{
				texSet.Add(e2.Current.Value.texture);
			}
		}
        
        foreach(Texture tex in texSet)
        {
            Resources.UnloadAsset(tex);
        }
	}
	
	public static void SetPrefabReferenceToSpriteSheet4(string resPath, BuildTarget target, string dir, int index, int total)
	{
		string str = CommonUtil.fileToString(dir + "/" + prefabListFileName);
		string[] paths = JsonConvert.DeserializeObject<string[]>(str);

		if(paths.Length < 50)
		{
			if(index > 0)
			{
				return;
			}
		}
		else
		{
			int groupNum = paths.Length / total;

			int groupBegin = groupNum * index;
			int groupEnd = groupNum * (index + 1);

			if(index == total - 1)
			{
				groupEnd += paths.Length % total;
			}

			string[] newPaths = new string[groupEnd - groupBegin];
			for(int i = groupBegin; i < groupEnd; i++)
			{
				newPaths[i - groupBegin] = paths[i];
			}

			paths = newPaths;
		}

		SetPrefabReferenceToSpriteSheet3(resPath, target, paths);
	}

	public static void SetPrefabReferenceToSpriteSheet3(string resPath, BuildTarget target, string[] paths)
	{
		setPrefabReference3 (resPath, target, paths);
		

	}

//	[MenuItem("Custom/OldProject/Prefab/SetPrefabReferenceToSpriteSheet")]
//	public static void SetPrefabReferenceToSpriteSheet()
//	{
//		SetPrefabReferenceToSpriteSheet2(CreateSpriteSheet.bundleDir, BuildTarget.Android);
//	}

	public static void SetPrefabReferenceToSpriteSheet4(string resPath, BuildTarget target, string[] dirs)
	{
		for(int i = 0; i < dirs.Length; i++)
		{
			string dir = dirs[i];
			if(!string.IsNullOrEmpty(Path.GetExtension(dir)))
			{
				if(dir.EndsWith(".prefab"))
				{
					string[] ps = new string[]{dir};
					setPrefabReference3(resPath, target, ps);
                }
			}
			else
			{
				CreatePrefabPathList2(dir);
				SetPrefabReferenceToSpriteSheet4(resPath, target, dir, 0, 5);
				SetPrefabReferenceToSpriteSheet4(resPath, target, dir, 1, 5);
				SetPrefabReferenceToSpriteSheet4(resPath, target, dir, 2, 5);
				SetPrefabReferenceToSpriteSheet4(resPath, target, dir, 3, 5);
				SetPrefabReferenceToSpriteSheet4(resPath, target, dir, 4, 5);
				DeletePrefabPathList2(dir);
			}
		}
		
		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();

		Dictionary<KeyValuePair<string, string>, SpriteIdInfo> idMap = getSpriteIdInfoMap(resPath, target);
		changeScriptSprite2(resPath, target, dirs, idMap);
	}




	public static void reSavePrefab(string prefabPath)
	{
		Object realPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(Object));
		GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;
		
		try
		{
			PrefabUtility.ReplacePrefab(prefab, realPrefab, ReplacePrefabOptions.ConnectToPrefab);
		}
		catch(System.Exception e)
		{
			Debug.LogException(e);
		}
		
		GameObject.DestroyImmediate(prefab);
	}

//	[MenuItem("Custom/OldProject/Modify/CheckImageType")]
//	public static void CheckImageType()
//	{
//		string[] prefabDirs = new string[]{"Assets/"};
//		for(int v = 0; v < prefabDirs.Length; v++)
//		{
//			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
//			for(int i = 0; i < paths.Length; i++)
//			{
//				string path = paths[i];
//				
//				Object realPrefab = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
//				GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;
//				Image[] images = prefab.GetComponentsInChildren<Image>(true);
//				
//
//				for(int j = 0; j < images.Length; j++)
//				{
//					Image image = images[j];
//
//					if(!(image is EvonyImage) && !(image is UIEmojiImage))
//					{
////						if(image.type == Image.Type.Filled)
//						{
//							Debug.LogError("test:" + path + " ");
//							Debug.LogError("test_1:" + image.type + " " + image.GetType());
//							Debug.LogError("test_2:" + image.gameObject.name + " " + image.gameObject.transform.parent.gameObject.name);
//						}
////						break;
//					}
//				}
//
//				GameObject.DestroyImmediate(prefab);
//			}
//		}
//	}

	[MenuItem("Custom/OldProject/Anim/CheckAnim")]
	public static void CheckAnim()
	{
		string[] prefabDirs = new string[]{ConfigTool.bundleDir[0] + "/Anim/", ConfigTool.bundleDir[0] + "/UIPackage/", ConfigTool.bundleDir[0] + "/" + Platform.ios + "/built_anim/", ConfigTool.bundleDir[0] + "/" + Platform.android + "/built_anim/"};
		string[] exts = new string[]{"*.anim", "*.controller", "*.mat"};

		for(int k = 0; k < exts.Length; k++)
		{
			for(int v = 0; v < prefabDirs.Length; v++)
			{
				if(!Directory.Exists(prefabDirs[v]))
				{
					continue;
				}
				string[] paths = Directory.GetFiles(prefabDirs[v], exts[k], SearchOption.AllDirectories);
				for(int i = 0; i < paths.Length; i++)
				{
					string path = paths[i];
					
					string[] temppaths = new string[]{path};
					string[] dependencies = AssetDatabase.GetDependencies(temppaths);

					for(int j = 0; j < dependencies.Length; j++)
					{
						string dependencePath = dependencies[j];
						if(dependencePath.EndsWith("jpg") || dependencePath.EndsWith("png"))
						{
							if(!dependencePath.Contains(ResourcesEx.SheetDirName))
							{
								Debug.LogError("error_object: " + path);
								Debug.LogError("error_object_2: " + dependencePath);
								break;
							}
						}
					}
				}
			}
		}
	}


	public static void setAnimReference (string resPath, BuildTarget target, string[] prefabDirs)
	{
		Dictionary<string, Dictionary<string, Sprite>> spriteSheetMap = new Dictionary<string, Dictionary<string, Sprite>>();
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath);

		for (int v = 0; v < prefabDirs.Length; v++) {
			string path = prefabDirs [v];
			string[] paths = null;
			if(!string.IsNullOrEmpty(Path.GetExtension(path)))
			{
				if(!path.EndsWith(".anim"))
				{
					continue;
				}
				paths = new string[]{path};
            }
			else
			{
				paths = Directory.GetFiles (path, "*.anim", SearchOption.AllDirectories);
			}

			for (int i = 0; i < paths.Length; i++)
			{
				AnimationClip clip = AssetDatabase.LoadAssetAtPath (paths [i], typeof(AnimationClip)) as AnimationClip;
				EditorCurveBinding[] curveBindings = AnimationUtility.GetObjectReferenceCurveBindings (clip);
				for (int j = 0; j < curveBindings.Length; j++)
				{
					if (curveBindings [j].propertyName == "m_Sprite")
					{
						System.Type t = curveBindings[j].type;

						bool isNeedSave = false;
						ObjectReferenceKeyframe[] keyFrame = AnimationUtility.GetObjectReferenceCurve (clip, curveBindings [j]);
						string preTexName = null;
						SortedDictionary<float, Texture> textureMap = new SortedDictionary<float, Texture>();
						for (int k = 0; k < keyFrame.Length; k++)
						{
							Sprite sprite = (Sprite)keyFrame [k].value;
							if(sprite != null)
							{
								string spritePath = AssetDatabase.GetAssetPath (sprite);
								string newSpriteName = spritePath.Replace (resPath + "/", "");
								string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
								string spriteSheetPath = "";
								Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, sprite.name, ref spriteSheetPath, target);
								if (tempSprite != null)
								{
									isNeedSave = true;
									keyFrame[k].value = tempSprite;	
									if(preTexName != tempSprite.texture.name)
									{
										textureMap.Add(keyFrame[k].time, tempSprite.texture);
										preTexName= tempSprite.texture.name;
									}
								}
//								else
//								{
//									Debug.LogError("getSprite failed: " + spritePath);
//								}
							}
						}

						if (isNeedSave)
						{
							SortedDictionary<float, Texture>.Enumerator e3 = textureMap.GetEnumerator();
							e3.MoveNext();
							string spriteSheetName = e3.Current.Value.name;
							string matPath = resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.spriteSheetMaterialSuffix + ".mat";
							if(File.Exists(matPath))
							{
								ObjectReferenceKeyframe[] matKeyFrames = new ObjectReferenceKeyframe[textureMap.Count];
								SortedDictionary<float, Texture>.Enumerator e2 = textureMap.GetEnumerator();
								int k = 0;
								while(e2.MoveNext())
								{
									spriteSheetName = e2.Current.Value.name;
									string matPath2 = null;
									if(t == typeof(SpriteRenderer))
									{
                                        matPath2 = resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.spriteSheetMaterialSuffix + ".mat";
									}
									else
									{
										matPath2 = resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat";
									}

									Object obj = AssetDatabase.LoadAssetAtPath(matPath2, typeof(Material));
									matKeyFrames[k] = new ObjectReferenceKeyframe ();
									matKeyFrames[k].time = e2.Current.Key;
									matKeyFrames[k].value = obj;
									k++;
								}
								
								EditorCurveBinding curveBinding2 = new EditorCurveBinding();
								curveBinding2.type = t;
								curveBinding2.path = curveBindings [j].path;
								if(t == typeof(SpriteRenderer))
								{
									curveBinding2.propertyName = "m_Materials.Array.data[0]";
								}
								else
								{
									curveBinding2.propertyName = "m_Material";
								}

								AnimationUtility.SetObjectReferenceCurve(clip, curveBinding2, matKeyFrames);
                            }
							else
							{
								string pngTexPath = resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + spriteSheetName + "/" + spriteSheetName + ".png";
								if(File.Exists(pngTexPath))
								{
									ObjectReferenceKeyframe[] matKeyFrames = new ObjectReferenceKeyframe[1];

									matKeyFrames[0] = new ObjectReferenceKeyframe ();
									matKeyFrames[0].time = 0;
									matKeyFrames[0].value = SpriteExtension.getBaseMaterial(t != typeof(SpriteRenderer));

									EditorCurveBinding curveBinding2 = new EditorCurveBinding();
									curveBinding2.type = t;
									curveBinding2.path = curveBindings [j].path;
									if(t == typeof(SpriteRenderer))
									{
										curveBinding2.propertyName = "m_Materials.Array.data[0]";
									}
									else
									{
										curveBinding2.propertyName = "m_Material";
									}

									AnimationUtility.SetObjectReferenceCurve(clip, curveBinding2, matKeyFrames);
								}
							}
                     
                            AnimationUtility.SetObjectReferenceCurve (clip, curveBindings [j], keyFrame);
                        }
                    }
                }
            }
        }


		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();

		HashSet<Texture> texSet = new HashSet<Texture>();
		Dictionary<string, Dictionary<string, Sprite>>.Enumerator e = spriteSheetMap.GetEnumerator();
		while(e.MoveNext())
		{
			Dictionary<string, Sprite>.Enumerator e2 = e.Current.Value.GetEnumerator();
			while(e2.MoveNext())
			{
				texSet.Add(e2.Current.Value.texture);
			}
		}

		foreach(Texture tex in texSet)
		{
			Resources.UnloadAsset(tex);
		}
	}

//	[MenuItem("Custom/OldProject/Prefab/deleteGrayController")]
//	public static void deleteGrayController()
//	{
//		string[] prefabDirs = new string[]{"Assets/"};
//		for(int v = 0; v < prefabDirs.Length; v++)
//		{
//			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
//			for(int i = 0; i < paths.Length; i++)
//			{
//				bool isNeedSave = false;
//				Object realPrefab = AssetDatabase.LoadAssetAtPath(paths[i], typeof(Object));
//				GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;
//				
//				ButtonGrayController[] images = prefab.GetComponentsInChildren<ButtonGrayController>(true);
//				for(int j = 0; j < images.Length; j++)
//				{
//					ButtonGrayController image = images[j];
//					GameObject.DestroyImmediate(image);
//					isNeedSave = true;
//				}
//				
//				if(isNeedSave)
//				{
//					PrefabUtility.ReplacePrefab(prefab, realPrefab, ReplacePrefabOptions.ConnectToPrefab);
//				}
//				
//				GameObject.DestroyImmediate(prefab);
//			}
//		}
//		
//		AssetDatabase.SaveAssets();
//	}

	[MenuItem("Custom/OldProject/Anim/SetAnimReferenceToSpriteSheet")]
	public static void SetAnimReferenceToSpriteSheet()
	{
		string[] prefabDirs = new string[]{ConfigTool.bundleDir[0] + "/Anim/", ConfigTool.bundleDir[0] + "/UIPackage/"};
        setAnimReference (ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget, prefabDirs);
	}

	[MenuItem("Custom/OldProject/Material/SetMaterialReferenceToSpriteSheet")]
	public static void SetMaterialReferenceToSpriteSheet()
	{
        SetMaterialReferenceToSpriteSheet2(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget, new string[]{ConfigTool.bundleDir[0] + "/" + "UIPackage"});
	}

	public static string convertShaderName(string shaderName)
	{
		if(shaderName == "Particles/Additive")
		{
			return "particle/add";
		}
		else if(shaderName == "Particles/Additive (Soft)")
		{
			return "particle/add/smooth";
		}
		else if(shaderName == "Particles/Alpha Blended")
		{
			return "particle/alphablend";
		}
		return shaderName;
	}

	public static void SetMaterialReferenceToSpriteSheet2(string resPath, BuildTarget target, string[] prefabDirs)
	{
		Dictionary<string, Dictionary<string, Sprite>> spriteSheetMap = new Dictionary<string, Dictionary<string, Sprite>>();
		
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath);

		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string path = prefabDirs[v];
			string[] paths = null;
			if(!string.IsNullOrEmpty(Path.GetExtension(path)))
			{
				if(!path.EndsWith(".mat"))
				{
					continue;
				}
				paths = new string[]{path};
			}
			else
			{
				paths = Directory.GetFiles(path, "*.mat", SearchOption.AllDirectories);
			}
			for(int i = 0; i < paths.Length; i++)
			{
				Material mat = AssetDatabase.LoadAssetAtPath(paths[i], typeof(Material)) as Material;
				Texture2D tex = mat.mainTexture as Texture2D;

				string spritePath = AssetDatabase.GetAssetPath(tex);
				
				string newSpriteName = spritePath.Replace(resPath + "/", "");
				string spriteSheetName = spriteSheetConfig.getSpriteSheetName(newSpriteName);

				if(spriteSheetName == null)
				{
                    Debug.LogError("not found sprite sheet: " + spritePath);
					Debug.LogError("mat path: " + paths[i]);
					continue;
				}
				SpriteSheetInfo info2 = null;
				spriteSheetConfig.TryGetValue(spriteSheetName, out info2);

				string spriteSheetPath = "";
				Sprite tempSprite = getSprite(resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, null, ref spriteSheetPath, target);

                if(tempSprite == null)
                {
                    Debug.LogError("not found sprite in sprite sheet: " + path + ", " + spritePath + ", " + spriteSheetName + ", " + newSpriteName);
					continue;
                }

				if(tempSprite != null)
				{
					string shaderName = mat.shader.name;

					string newShaderName = null;
					if(info2.split_alpha_type == SplitAlphaType.NONE)
					{
						newShaderName = "custom" + "/" + convertShaderName(shaderName);
					}
					else if(info2.split_alpha_type == SplitAlphaType.SPLIT_TEX)
					{
						newShaderName = "custom/splitalpha" + "/" + convertShaderName(shaderName);
					}
					else
					{
						newShaderName = "custom/splitalpha2" + "/" + convertShaderName(shaderName);
					}

					Shader newShader = Shader.Find(newShaderName);
					if(newShader != null)
					{
						mat.shader = newShader;

						SpriteInfo info = tempSprite.GetSpriteInfo();
						mat.SetSpriteRect(info.rect, tempSprite.texture.width, tempSprite.texture.height, "_RealSpriteRect_ST");
						Rect rect = info.getOutterSpriteRect();
						mat.SetSpriteRect(rect, tempSprite.texture.width, tempSprite.texture.height, "_SpriteRect_ST");
					}

					if(info2.split_alpha_type == SplitAlphaType.NONE)
					{
					}
					else if(info2.split_alpha_type == SplitAlphaType.SPLIT_TEX)
					{
                    }
                    else
                    {
						mat.SetFloat("_Horizontal", info2.split_alpha_type == SplitAlphaType.HORIZONTAL? 1: 0);
                    }



					mat.mainTexture = tempSprite.texture;

					if(info2.split_alpha_type == SplitAlphaType.SPLIT_TEX)
					{
						string ext = ".png";
						if(spritePath.EndsWith(ext))
						{
							string alphaPath = AssetDatabase.GetAssetPath(tempSprite.texture);
							alphaPath = GetAlphaTexPath(alphaPath);
							Texture2D alphaTex = AssetDatabase.LoadAssetAtPath(alphaPath, typeof(Texture2D)) as Texture2D;
                            mat.SetTexture("_MaskTex", alphaTex);
                        }
                    }
                }
            }
        }
        
		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();


		HashSet<Texture> texSet = new HashSet<Texture>();
		Dictionary<string, Dictionary<string, Sprite>>.Enumerator e = spriteSheetMap.GetEnumerator();
		while(e.MoveNext())
		{
			Dictionary<string, Sprite>.Enumerator e2 = e.Current.Value.GetEnumerator();
			while(e2.MoveNext())
			{
				texSet.Add(e2.Current.Value.texture);
			}
		}
        
        foreach(Texture tex in texSet)
        {
            Resources.UnloadAsset(tex);
        }
	}

	private static int calIsolationWidth(int width)
	{
		int alphaWidth = width;
		alphaWidth += 2;
		int alphaTempWidth = alphaWidth / 3;
		if(alphaWidth % 3 != 0)
		{
			alphaTempWidth++;
		}
		alphaWidth = alphaTempWidth;
		return alphaWidth;
	}

    public static void SeperateRGBAandlphaChannel(string _texPath, string outputPath)
    {
		Resources.UnloadUnusedAssets();
		System.GC.Collect();

        string assetRelativePath = GetRelativeAssetPath(_texPath);

		TexAttributeEx.enbleSetSpriteSheet = false;
		Dictionary<string, TempTextureFormat> dic = SetTextureReadable(assetRelativePath);
		TexAttributeEx.enbleSetSpriteSheet = true;

		Texture2D sourcetex = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(Texture2D)) as Texture2D;  //not just the textures under Resources file
		sourcetex.filterMode = FilterMode.Point;
        
        if (!sourcetex)
        {
            Debug.Log("Load Texture Failed : " + assetRelativePath);
            return;
        }
        if (!HasAlphaChannel(sourcetex))
        {
            Debug.Log("Texture does not have Alpha channel : " + assetRelativePath);
            return;
        }

		Texture2D rgbTex = null;
		Texture2D alphaTex = null;
		if(compress)
		{
			if(isolation)
			{
				rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, false);

				int alphaWidth = calIsolationWidth(sourcetex.width);
				
				int powerOfTwoWidth = Mathf.ClosestPowerOfTwo(alphaWidth);
				if(alphaWidth > powerOfTwoWidth)
				{
					powerOfTwoWidth *= 2;
				}
				alphaWidth = powerOfTwoWidth;
				
				alphaTex = new Texture2D((int)(alphaWidth * sizeScale), (int)(sourcetex.height * sizeScale), TextureFormat.RGB24, false);
				
				int widthPixelNum = Mathf.CeilToInt(sourcetex.width / 3f);
				int[] pixelOffsets = new int[4];
				pixelOffsets[0] = 0;
				pixelOffsets[1] = widthPixelNum;
				pixelOffsets[2] = 2 * widthPixelNum;
				pixelOffsets[3] = sourcetex.width;
				
				for (int j = 0; j < sourcetex.height; ++j)
				{
					Color[] alphaColors = new Color[alphaWidth];
					for(int k = 0; k < pixelOffsets.Length - 1; k++)
					{
						int start = pixelOffsets[k] - 1;
						int end = pixelOffsets[k + 1] + 1;
						
						int realStart = Mathf.Max(start, 0);
						int realEnd = Mathf.Min(end, sourcetex.width);
						
						for(int i = realStart; i < realEnd; i++)
						{
							Color color = sourcetex.GetPixel(i, j);
							Color rgbColor = color;
							rgbTex.SetPixel(i, j, rgbColor);
							
							float alpha = rgbColor.a;
							alphaColors[i - start][k] = alpha;
						}
					}
					
					alphaTex.SetPixels(0, j, alphaColors.Length, 1, alphaColors);
				}
			}
			else
			{
				rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, false);
				int alphaWidth = sourcetex.width;
				int alphaTempWidth = alphaWidth / 3;
				if(alphaWidth % 3 != 0)
				{
					alphaTempWidth++;
				}
				alphaWidth = alphaTempWidth;
				
				int powerOfTwoWidth = Mathf.ClosestPowerOfTwo(alphaWidth);
				if(alphaWidth > powerOfTwoWidth)
				{
					powerOfTwoWidth *= 2;
				}
				alphaWidth = powerOfTwoWidth;
				
				alphaTex = new Texture2D((int)(alphaWidth * sizeScale), (int)(sourcetex.height * sizeScale), TextureFormat.RGB24, false);
				
				for (int j = 0; j < sourcetex.height; ++j)
				{
					int alphaIndex = 0;
					Color alphaColor = new Color();

					for (int i = 0; i < sourcetex.width; ++i)
					{
						Color color = sourcetex.GetPixel(i, j);
						Color rgbColor = color;
						rgbTex.SetPixel(i, j, rgbColor);
						
						alphaColor[alphaIndex++] = rgbColor.a;
						if(alphaIndex >= 3 || i == sourcetex.width - 1)
						{
							alphaIndex = 0;
							alphaTex.SetPixel((int)(i / 3 * sizeScale), (int)(j * sizeScale), alphaColor);
						}
					}
				}
			}
		}
		else
		{
			rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, false);
			alphaTex = new Texture2D((int)(sourcetex.width * sizeScale), (int)(sourcetex.height * sizeScale), TextureFormat.RGB24, false);

			for (int j = 0; j < sourcetex.height; ++j)
			{
				Color[] srcColors = sourcetex.GetPixels(0, j, sourcetex.width, 1);

//				for (int i = 0; i < sourcetex.width; ++i)
//				{
//					if(srcColors[i].a == 0)
//					{
//						srcColors[i].r = srcColors[i].g = srcColors[i].b = 0;
//					}
//				}

				rgbTex.SetPixels(0, j, sourcetex.width, 1, srcColors);

				for (int i = 0; i < sourcetex.width; ++i)
				{
					Color color = srcColors[i];
					Color alphaColor = color;
					alphaColor.r = color.a;
					alphaColor.g = color.a;
					alphaColor.b = color.a;
					srcColors[i] = alphaColor;
				}

				alphaTex.SetPixels(0, j, sourcetex.width, 1, srcColors);
			}

//			Color32[] c32 = sourcetex.GetPixels32(0);
//			Color32[] temp = new Color32[c32.Length];
//			for(int s = 0; s < c32.Length; s++)
//			{
//				temp[s] = c32[s];
//				if(temp[s].a == 0)
//				{
//					temp[s].r = 0;
//					temp[s].b = 0;
//					temp[s].b = 0;
//				}
//			}
//			rgbTex.SetPixels32(temp);
//
//			for(int s = 0; s < c32.Length; s++)
//			{
//				temp[s] = c32[s];
//				temp[s].r = temp[s].a;
//				temp[s].g = temp[s].a;
//				temp[s].b = temp[s].a;
//			}
//			alphaTex.SetPixels32(temp);
		}

		Resources.UnloadAsset(sourcetex);
		sourcetex = null;
		Resources.UnloadUnusedAssets();
		System.GC.Collect();
		
		//		Texture2D rgbTex = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, false);
//		int alphaPixelNum = sourcetex.width * sourcetex.height;
//
//		int alphaRgbNum = alphaPixelNum / 3;
//		if(alphaPixelNum % 3 != 0)
//		{
//			alphaRgbNum++;
//		}
//
//		int power2AlphaNum = Mathf.ClosestPowerOfTwo(alphaRgbNum);
//		if(alphaRgbNum > power2AlphaNum)
//		{
//			power2AlphaNum *= 2;
//		}
//		alphaRgbNum = power2AlphaNum;
//
//		float sq = Mathf.Sqrt(alphaRgbNum);
//
//		int alphaWidth = Mathf.FloorToInt(sq);
//		int tempWidth = Mathf.ClosestPowerOfTwo(alphaWidth);
//		if(alphaWidth > tempWidth)
//		{
//			tempWidth *= 2;
//		}
//		alphaWidth = tempWidth;
//		int alphaHeight = alphaRgbNum / alphaWidth;
//
//		int alpha_i = 0;
//		int alpha_j = 0;
//
//		Texture2D alphaTex = new Texture2D((int)(alphaWidth * sizeScale), (int)(alphaHeight * sizeScale), TextureFormat.RGB24, false);
//		for (int j = 0; j < sourcetex.height; ++j)
//		{
//			int alphaIndex = 0;
//			Color alphaColor = new Color();
//			for (int i = 0; i < sourcetex.width; ++i)
//			{
//				Color color = sourcetex.GetPixel(i, j);
//				Color rgbColor = color;
//				rgbTex.SetPixel(i, j, rgbColor);
//
//				alphaColor[alphaIndex++] = color.a;
//				if(alphaIndex >= 3)
//				{
//					alphaIndex = 0;
//					alphaTex.SetPixel((int)(alpha_i * sizeScale), (int)(alpha_j * sizeScale), alphaColor);
//					alpha_i++;
//					if(alpha_i >= alphaWidth)
//					{
//						alpha_i = 0;
//						alpha_j++;
//					}
//				}
//			}
//		}

		rgbTex.Apply();
		alphaTex.Apply();

		{
			byte[] bytes = rgbTex.EncodeToPNG();
			string fileName = Path.GetFileName(_texPath);
			_texPath = outputPath + "/" + fileName;
			string rgbFilePath = GetRGBTexPath(_texPath);
			CommonUtil.bytesToFile(rgbFilePath, bytes);
		}
		{
			byte[] bytes = alphaTex.EncodeToPNG();
			string alphaFilePath = GetAlphaTexPath(_texPath);
			CommonUtil.bytesToFile(alphaFilePath, bytes);
		}

		ReverseTextureReadable(assetRelativePath, dic);

		Debug.Log("Succeed to seperate RGB and Alpha channel for texture : " + assetRelativePath);
    }
	
    static bool HasAlphaChannel(Texture2D _tex)
    {
		return true;
//        for (int i = 0; i < _tex.width; ++i)
//		{
//			for (int j = 0; j < _tex.height; ++j)
//            {
//                Color color = _tex.GetPixel(i, j);
//
//                float alpha = color.a;
//                if (alpha < 1.0f - 0.001f)
//                {
//                    return true;
//                }
//            }
//		}
//        return false;
    }

	public static Dictionary<string, TempTextureFormat> GetPlatformTextureFormatMap(this TextureImporter ti)
	{
		if (ti == null)
		{
			return null;
		}

		Dictionary<string, TempTextureFormat> dic = new Dictionary<string, TempTextureFormat>();
		string[] p = new string[]{"Android", "iPhone", "Standalone"};
		for(int i = 0; i < p.Length; i++)
		{
			TempTextureFormat androidFormat = new TempTextureFormat();
			bool ret = ti.GetPlatformTextureSettings(p[i], out androidFormat.maxSize, out androidFormat.format, out androidFormat.quality);
			if(ret)
			{
				dic.Add(p[i], androidFormat);
				ti.ClearPlatformTextureSettings(p[i]);
			}
		}

		TempTextureFormat defaultFormat = new TempTextureFormat();
		TextureImporterPlatformSettings setting = ti.GetDefaultPlatformTextureSettings();
		defaultFormat.maxSize = setting.maxTextureSize;
		defaultFormat.quality = ti.compressionQuality;
		defaultFormat.compression = ti.textureCompression;
		dic.Add("Default", defaultFormat);

		return dic;
	}

	public static void SetPlatformTextureFormatMap(this TextureImporter ti, Dictionary<string, TempTextureFormat> dic)
	{
		if (ti == null)
		{
			return;
		}

		{
			Dictionary<string, TempTextureFormat>.Enumerator e = dic.GetEnumerator();
			while (e.MoveNext())
			{
				if (e.Current.Key == "Default")
				{
					ti.maxTextureSize = e.Current.Value.maxSize;
					ti.compressionQuality = e.Current.Value.quality;
					ti.textureCompression = e.Current.Value.compression;
					break;
				}
			}
		}

		{
			Dictionary<string, TempTextureFormat>.Enumerator e = dic.GetEnumerator();
			while (e.MoveNext())
			{
				if (e.Current.Key != "Default")
				{
					TexAttributeEx.SetPlatformTextureSettings(ti, e.Current.Key, e.Current.Value.maxSize, e.Current.Value.format, e.Current.Value.quality);
				}
			}
		}
	}

	public static Dictionary<string,TempTextureFormat> SetTextureReadable(string _relativeAssetPath)
    {
		AssetImporter assetImporter = TextureImporter.GetAtPath(_relativeAssetPath);
		if(assetImporter == null)
		{
			return null;
		}

		if(assetImporter is TextureImporter)
		{
            TextureImporter ti = (TextureImporter)assetImporter;

			Dictionary<string, TempTextureFormat> dic = GetPlatformTextureFormatMap(ti);

            ti.textureCompression = TextureImporterCompression.Uncompressed;
            ti.isReadable = true;
            AssetDatabase.ImportAsset(_relativeAssetPath);
            return dic;
		}
        else if(assetImporter is IHVImageFormatImporter)
        {
            IHVImageFormatImporter ti = (IHVImageFormatImporter)assetImporter;
            ti.isReadable = true;
            AssetDatabase.ImportAsset(_relativeAssetPath);
            return null;
        }

        return null;
    }
   
	public static void ReverseTextureReadable(string _relativeAssetPath, Dictionary<string, TempTextureFormat> dic)
	{
		AssetImporter assetImporter = TextureImporter.GetAtPath(_relativeAssetPath);
		if(assetImporter == null)
		{
			return;
		}

        if (assetImporter is TextureImporter)
        {
            TextureImporter ti = (TextureImporter)assetImporter;
			SetPlatformTextureFormatMap(ti, dic);
            ti.isReadable = false;
            AssetDatabase.ImportAsset(_relativeAssetPath);
        }
        else if (assetImporter is IHVImageFormatImporter)
        {
            IHVImageFormatImporter ti = (IHVImageFormatImporter)assetImporter;
            ti.isReadable = false;
            AssetDatabase.ImportAsset(_relativeAssetPath);
        }
	}

    static bool IsTextureFile(string _path)
    {
        string path = _path.ToLower();
        return path.EndsWith(".psd") || path.EndsWith(".tga") || path.EndsWith(".png") || path.EndsWith(".jpg") || path.EndsWith(".dds") || path.EndsWith(".bmp") || path.EndsWith(".tif") || path.EndsWith(".gif");
    }

    public static string GetRGBTexPath(string _texPath)
    {
		return GetTexPath(_texPath, rgbSuffix + ".");
    }

    static string GetAlphaTexPath(string _texPath)
    {
		return GetTexPath(_texPath, ResourcesEx.SpriteSheetAlphaSuffix + ".");
    }

    static string GetTexPath(string _texPath, string _texRole)
    {
        string result = _texPath.Replace(".", _texRole);
        string postfix = GetFilePostfix(_texPath);
        return result.Replace(postfix, ".png");
    }

    static string GetRelativeAssetPath(string _fullPath)
    {
        _fullPath = GetRightFormatPath(_fullPath);
        int idx = _fullPath.IndexOf("Assets");
        string assetRelativePath = _fullPath.Substring(idx);
        return assetRelativePath;
    }

    static string GetRightFormatPath(string _path)
    {
        return _path.Replace("\\", "/");
    }

    static string GetFilePostfix(string _filepath)   //including '.' eg ".tga", ".dds"
    {
        string postfix = "";
        int idx = _filepath.LastIndexOf('.');
        if (idx > 0 && idx < _filepath.Length)
            postfix = _filepath.Substring(idx, _filepath.Length - idx);
        return postfix;
    }

	
//	[MenuItem("Custom/OldProject/Sprite/MoveAnimToSheet")]
//	public static void MoveAnimToSheet()
//	{
//		for(int i = 0; i < TexturePackerImporter.spriteSheetInfos.Length; i++)
//		{
//			SpriteSheetInfo2 info = TexturePackerImporter.spriteSheetInfos[i];
//			string srcPath = info.getSrcPath();
//			string[] paths = Directory.GetDirectories(srcPath, "*", SearchOption.TopDirectoryOnly);
//			for(int j = 0; j < paths.Length; j++)
//			{
//				string path = paths[j];
//				string AnimPath = path + "/" + "Anim";
//				if(Directory.Exists(AnimPath))
//				{
//					string outputPath = AnimPath.Replace(srcPath, info.getOutputPath());
//					AssetDatabase.MoveAsset(AnimPath, outputPath);
//				}
//			}
//		}
//	}

//	[MenuItem("Custom/OldProject/Sprite/MoveAnimToSprite")]
//	public static void MoveAnimToSprite()
//	{
//		for(int i = 0; i < TexturePackerImporter.spriteSheetInfos.Length; i++)
//		{
//			SpriteSheetInfo2 info = TexturePackerImporter.spriteSheetInfos[i];
//			string srcPath = info.getOutputPath();
//			if(!Directory.Exists(srcPath))
//			{
//				return;
//			}
//			string[] paths = Directory.GetDirectories(srcPath, "*", SearchOption.TopDirectoryOnly);
//			for(int j = 0; j < paths.Length; j++)
//			{
//				string path = paths[j];
//				string AnimPath = path + "/" + "Anim";
//				if(Directory.Exists(AnimPath))
//				{
//					string outputPath = AnimPath.Replace(srcPath, info.getSrcPath());
//					AssetDatabase.MoveAsset(AnimPath, outputPath);
//				}
//			}
//		}
//	}

	[MenuItem("Custom/OldProject/Sprite/CreateSpriteSheetMeta")]
	public static void CreateSpriteSheetMeta()
	{
        createSpriteSheetMeta(ConfigTool.bundleDir[0], EditorUserBuildSettings.activeBuildTarget);
	}

	public static void CreateSpriteSheetMeta2(string resPath, BuildTarget target, HashSet<string> hashSet)
	{
		createSpriteSheetMeta(resPath, target, hashSet);
//
		AssetDatabase.Refresh();
	}

	public static void CreateSpriteSheetPrefab2(string resPath, HashSet<string> hashSet)
	{
		createSpriteSheetPrefab(resPath, hashSet);
		//
		AssetDatabase.Refresh();
	}

	public static void createSpriteSheetMeta(string resPath,BuildTarget target, HashSet<string> hashSet = null)
	{
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath, target.getPlatform());
		string parentPath = resPath + "/" + EditorCommonTool.getSheetDirName(target);
		SpriteSheetConfig.KeyCollection keys = spriteSheetConfig.Keys;
		foreach(string spriteSheetName in keys)
		{
			string outputPath = parentPath + "/" + spriteSheetName;
			if(hashSet != null)
			{
				if(!hashSet.Contains(spriteSheetName))
				{
					continue;
				}
			}

			CommonUtil.stringToFile(outputPath + "/" + BundleManager.dependenceName + ".bytes", "");
		}
	}

	[MenuItem("Custom/OldProject/Sprite/CreateSpriteSheetPrefab")]
	public static void CreateSpriteSheetPrefab()
	{
		createSpriteSheetPrefab(ConfigTool.bundleDir[0]);
	}

	public static void createSpriteSheetPrefab(string resPath, HashSet<string> hashSet = null)
	{
		SpriteSheetConfig spriteSheetConfig = EditorCommonTool.getSpriteSheetConfig(resPath);

		BuildTarget[] targets = new BuildTarget[]{BuildTarget.Android, EditorCommonTool.build_target_ios};
		for(int i = 0; i < targets.Length; i++)
		{
			string parentPath = resPath + "/" + EditorCommonTool.getSheetDirName(targets[i]);
			
			SpriteSheetConfig.KeyCollection keys = spriteSheetConfig.Keys;
			foreach(string spriteSheetName in keys)
			{
				string outputPath = parentPath + "/" + spriteSheetName;
				
				Directory.CreateDirectory(outputPath);
				
				if(hashSet != null)
				{
					if(!hashSet.Contains(spriteSheetName))
					{
						continue;
					}
				}

				string texFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ".png";
				bool isPng = File.Exists(texFilePath);
				if(!isPng)
				{
					texFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ".jpg";
				}

				string depFilePath = outputPath + "/" + BundleManager.dependenceName + ".bytes";
				string configFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetConfigSuffix + ".bytes";

				string alphaTexFilePath = null;
				string matFilePath = null;
				string uiMatFilePath = null;
				if(targets[i] == BuildTarget.Android && isPng)
				{
					alphaTexFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.SpriteSheetAlphaSuffix + ".png";
					matFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetMaterialSuffix + ".mat";
					uiMatFilePath = outputPath + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat";
				}

				GameObject obj = new GameObject();
				SpriteSheetResObj configObj = obj.AddComponent<SpriteSheetResObj>();
				configObj.tex = AssetDatabase.LoadAssetAtPath(texFilePath, typeof(Texture2D)) as Texture2D;
				configObj.config_file = AssetDatabase.LoadAssetAtPath(configFilePath, typeof(TextAsset)) as TextAsset;
				configObj.dependence_file = AssetDatabase.LoadAssetAtPath(depFilePath, typeof(TextAsset)) as TextAsset;

				if(alphaTexFilePath != null)
				{
					configObj.tex_alpha = AssetDatabase.LoadAssetAtPath(alphaTexFilePath, typeof(Texture2D)) as Texture2D;
					configObj.material = AssetDatabase.LoadAssetAtPath(matFilePath, typeof(Material)) as Material;
					configObj.material_ui = AssetDatabase.LoadAssetAtPath(uiMatFilePath, typeof(Material)) as Material;
				}

				PrefabUtility.CreatePrefab(outputPath + "/" + spriteSheetName + ".prefab", obj, ReplacePrefabOptions.ConnectToPrefab);
				GameObject.DestroyImmediate(obj);
			}
		}
		AssetDatabase.SaveAssets();
	}

	public static void copySpriteSheetToAndroid(HashSet<string> hashSet = null)
	{
		string[] exts = new string[MaterialTextureForETC1.exts.Length + 1];
		
		for(int i = 0; i < MaterialTextureForETC1.exts.Length; i++)
		{
			exts[i] = MaterialTextureForETC1.exts[i];
		}
		exts[exts.Length - 1] = ".tpsheet";
		



		string iosOutputPath = ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.build_target_ios);
		string androidOutputPath = ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getSheetDirName(BuildTarget.Android);

		string[] dirPaths = Directory.GetDirectories (iosOutputPath, "*", SearchOption.TopDirectoryOnly);
		for(int u = 0; u < dirPaths.Length; u++)
		{
			string dirPath = dirPaths[u];
			string spriteSheetName = dirPath.Replace(iosOutputPath + "/", "");

			if(hashSet != null)
			{
				if(!hashSet.Contains(spriteSheetName))
				{
					continue;
				}
			}

			for(int j = 0; j < exts.Length; j++)
			{
				string ext = exts[j];
				string[] paths = Directory.GetFiles (dirPath, "*" + ext, SearchOption.AllDirectories);
				for(int k = 0; k < paths.Length; k++)
				{
					string path = paths[k];
					string outPath = path.Replace(iosOutputPath, androidOutputPath);
					string dir = Path.GetDirectoryName(outPath);
					Directory.CreateDirectory(dir);

					CommonUtil.Copy(path, outPath);
				}
			}
		}

		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/Material/CreateFootPrintMaterial")]
	public static void CreateFootPrintMaterial()
	{
		string shaderPrefix = "custom/";
		string shaderName = "footprint";
		string materialPath = "material/footprint.mat";
		string spritePath = "Sprite/Map/footprint.png";
		string ext = ".png";

		if(EditorSwitchConfig.spriteSheetMode != SpriteSheetMode.texturepacker)
		{
			Shader shader = Shader.Find(shaderPrefix + shaderName);
			Material material = new Material(shader);
			string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
			AssetDatabase.CreateAsset (material, realMaterialPath);
		}
		else
		{
			Platform platform = EditorUserBuildSettings.activeBuildTarget.getPlatform();
            SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(ConfigTool.bundleDir[0], platform);
			if(config == null)
			{
				return;
			}

			string spriteSheetName = config.getSpriteSheetName(spritePath);
			string spriteSheetPath = ResourcesEx.SheetDirName + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix;
			string alphaSpriteSheetPath = spriteSheetPath + ResourcesEx.SpriteSheetAlphaSuffix;
			SpriteSheetInfo info = null;
			config.TryGetValue(spriteSheetName, out info);

			Material material = null;
			if(info.split_alpha_type == SplitAlphaType.NONE)
			{
				Shader shader = Shader.Find(shaderPrefix + shaderName);
				material = new Material(shader);
			}
			else if(info.split_alpha_type == SplitAlphaType.SPLIT_TEX)
			{
				Shader shader = Shader.Find(shaderPrefix + "splitalpha" + "/" + shaderName);
				material = new Material(shader);
				Texture2D tex = AssetDatabase.LoadAssetAtPath(ConfigTool.bundleDir[0] + "/" + platform + "/" + alphaSpriteSheetPath + ext, typeof(Texture2D)) as Texture2D;
				material.SetTexture("_MaskTex", tex);
			}
			else
			{
				Shader shader = Shader.Find(shaderPrefix + "splitalpha2" + "/" + shaderName);
				material = new Material(shader);
				material.SetFloat("_Horizontal", info.split_alpha_type == SplitAlphaType.HORIZONTAL? 1: 0);
			}

			
			string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
			AssetDatabase.CreateAsset (material, realMaterialPath);
		}
		
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/Material/CreateMenuMaterial")]
	public static void CreateMenuMaterial()
	{
		string shaderPrefix = "custom/";
		string shaderName = "menu";
		string materialPath = "material/menu.mat";
		string spritePath = "Sprite/UI/UIBest/round.png";
		string ext = ".png";

		if(EditorSwitchConfig.spriteSheetMode != SpriteSheetMode.texturepacker)
		{
			Shader shader = Shader.Find(shaderPrefix + shaderName);
			Material material = new Material(shader);
			string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
			AssetDatabase.CreateAsset (material, realMaterialPath);
		}
		else
		{
			Platform platform = EditorUserBuildSettings.activeBuildTarget.getPlatform();
            SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(ConfigTool.bundleDir[0], platform);
			if(config == null)
			{
				return;
			}

			string spriteSheetName = config.getSpriteSheetName(spritePath);
			string spriteSheetPath = ResourcesEx.SheetDirName + "/" + spriteSheetName + "/" + spriteSheetName + ResourcesEx.SpriteSheetTexSuffix;
			string alphaSpriteSheetPath = spriteSheetPath + ResourcesEx.SpriteSheetAlphaSuffix;
			SpriteSheetInfo info = null;
			config.TryGetValue(spriteSheetName, out info);
			
			Material material = null;
			if(info.split_alpha_type == SplitAlphaType.NONE)
			{
				Shader shader = Shader.Find(shaderPrefix + shaderName);
				material = new Material(shader);
			}
			else if(info.split_alpha_type == SplitAlphaType.SPLIT_TEX)
			{
				Shader shader = Shader.Find(shaderPrefix + "splitalpha" + "/" + shaderName);
				material = new Material(shader);
				Texture2D tex = AssetDatabase.LoadAssetAtPath(ConfigTool.bundleDir[0] + "/" + platform + "/" + alphaSpriteSheetPath + ext, typeof(Texture2D)) as Texture2D;
				material.SetTexture("_MaskTex", tex);
			}
			else
			{
				Shader shader = Shader.Find(shaderPrefix + "splitalpha2" + "/" + shaderName);
				material = new Material(shader);
				material.SetFloat("_Horizontal", info.split_alpha_type == SplitAlphaType.HORIZONTAL? 1: 0);
			}
			
			string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
			AssetDatabase.CreateAsset (material, realMaterialPath);
		}

		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}
	
	[MenuItem("Custom/OldProject/Material/CreateGrayMaterial")]
	static void CreateGrayMaterial()
	{
		string shaderPrefix = "custom/";

		{
			string shaderName = "gray/ui";
			string materialPath = "material/gray_ui.mat";
			
			{
				Shader shader = Shader.Find(shaderPrefix + shaderName);
				Material material = new Material(shader);
				string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
				AssetDatabase.CreateAsset (material, realMaterialPath);
			}
			
			Platform[] platforms = new Platform[]{Platform.android, Platform.ios};
			for(int j = 0; j < platforms.Length; j++)
			{
				Shader shader = Shader.Find(shaderPrefix + platforms[j] + "/" + shaderName);
				Material material = new Material(shader);

				string realMaterialPath = ConfigTool.bundleDir[0] + "/" + platforms[j] + "/" + materialPath;
				AssetDatabase.CreateAsset (material, realMaterialPath);
			}
		}

		{
			string shaderName = "gray/sprite";
			string materialPath = "material/gray.mat";
			
			{
				Shader shader = Shader.Find(shaderPrefix + shaderName);
				Material material = new Material(shader);
				string realMaterialPath = ConfigTool.bundleDir[0] + "/" + materialPath;
				AssetDatabase.CreateAsset (material, realMaterialPath);
			}
			
			Platform[] platforms = new Platform[]{Platform.android, Platform.ios};
			for(int j = 0; j < platforms.Length; j++)
			{
				Shader shader = Shader.Find(shaderPrefix + platforms[j] + "/" + shaderName);
				Material material = new Material(shader);
				
				string realMaterialPath = ConfigTool.bundleDir[0] + "/" + platforms[j] + "/" + materialPath;
				AssetDatabase.CreateAsset (material, realMaterialPath);
			}
		}
		
		AssetDatabase.Refresh();
	}

	[MenuItem("Assets/Custom/OldProject/CheckSpriteUsed")]
	static void CheckSprite()
	{
		Object obj = Selection.activeObject;
		if(obj is Texture2D)
		{
			string[] prefabDirs = new string[]{"Assets/"};
			for(int v = 0; v < prefabDirs.Length; v++)
			{
				string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
				for(int i = 0; i < paths.Length; i++)
				{
					bool find = false;
					Object realPrefab = AssetDatabase.LoadAssetAtPath(paths[i], typeof(Object));
					GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;
					
					SpriteRenderer[] renders = prefab.GetComponentsInChildren<SpriteRenderer>(true);
					for(int j = 0; j < renders.Length; j++)
					{
						SpriteRenderer render = renders[j];
						Sprite sprite = render.sprite;
						if(sprite != null && sprite.texture == obj)
						{
							find = true;
							break;
						}
					}

					if(!find)
					{
						Image[] images = prefab.GetComponentsInChildren<Image>(true);
						for(int j = 0; j < images.Length; j++)
						{
							Image image = images[j];
							Sprite sprite = image.sprite;
							if(sprite != null && sprite.texture == obj)
							{
								find = true;
								break;
							}
						}
					}

					if(!find)
					{
						Button[] buttons = prefab.GetComponentsInChildren<Button>(true);
						for(int j = 0; j < buttons.Length; j++)
						{
							Button button = buttons[j];
							if(button.transition == Selectable.Transition.SpriteSwap)
							{
								SpriteState state = button.spriteState;
								Sprite sprite = state.pressedSprite;
								if(sprite != null && sprite.texture == obj)
								{
									find = true;
									break;
								}
								
								sprite = state.disabledSprite;
								if(sprite != null && sprite.texture == obj)
								{
									find = true;
									break;
								}
								
								sprite = state.highlightedSprite;
								if(sprite != null && sprite.texture == obj)
								{
									find = true;
									break;
								}
							}
						}
					}

					GameObject.DestroyImmediate(prefab);
					if(find)
					{
						Debug.Log(obj.name + ":" + paths[i]);
//						return;
					}
				}
			}
		}
	}

	[MenuItem("Assets/Custom/OldProject/CheckReference")]
	static void CheckReference()
	{
 		Object obj = Selection.activeObject;

		string s = obj.name + "\n";

		string objPath = AssetDatabase.GetAssetPath(obj);
		string[] prefabDirs = new string[]{"Assets/"};
		string[] exts = new string[]{"*.prefab", "*.mat", "*.anim"};
		for(int k = 0; k < exts.Length; k++)
		{
			for(int v = 0; v < prefabDirs.Length; v++)
			{
				string[] paths = Directory.GetFiles(prefabDirs[v], exts[k], SearchOption.AllDirectories);
				for(int i = 0; i < paths.Length; i++)
				{
					string[] tempPath = new string[]{paths[i]};
					string[] dp = AssetDatabase.GetDependencies(tempPath);
					for(int j = 0; j < dp.Length; j++)
					{
						if(dp[j].EndsWith(objPath))
						{
							if(paths[i] != objPath)
							{
								s += paths[i] + "\n";
								break;
							}
						}
					}
				}
			}
		}

		Debug.Log(s);
	}

	[MenuItem("Custom/OldProject/printPrefabCount")]
	static void printPrefabCount()
	{
		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
			Debug.Log("prefab count:" + paths.Length);
		}
	}

	[MenuItem("Custom/OldProject/Prefab/ResetPrefab")]
	public static void ResetPrefab()
	{
        string path = ResourcesEx.BundleResDir + "/RawUI/UIPackage/prefab/Evony1/Loading_role.prefab";
		
		bool isNeedSave = false;
		Object realPrefab = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
		GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;

		Image[] images = prefab.GetComponentsInChildren<Image>(true);
		for(int j = 0; j < images.Length; j++)
		{
			Image image = images[j];
			Sprite sprite = image.sprite;
			if(sprite != null)
			{
				string spritePath = AssetDatabase.GetAssetPath(sprite);

				string dir = Path.GetDirectoryName(spritePath);
				Sprite newSprite = AssetDatabase.LoadAssetAtPath(dir + "/" + sprite.texture.name + "/" + sprite.name + ".png", typeof(Sprite)) as Sprite;

				if(newSprite != null)
				{
					image.sprite = newSprite;
					isNeedSave = true;
				}
			}
		}
		
		if(isNeedSave)
		{
			try
			{
				PrefabUtility.ReplacePrefab(prefab, realPrefab, ReplacePrefabOptions.ConnectToPrefab);
			}
			catch(System.Exception e)
			{
				Debug.LogException(e);
			}
		}
		
		GameObject.DestroyImmediate(prefab);
		
		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}

	[MenuItem("Assets/Custom/OldProject/cutTex")]
	public static void cutTex()
	{
		if(Selection.assetGUIDs == null || Selection.assetGUIDs.Length <= 0)
		{
			return;
		}

		string p = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);;
		string srcPath = p;
		string destPath = p + "_cut_tex";

		Directory.CreateDirectory(destPath);
		string[] jpgPaths = Directory.GetFiles(srcPath, "*");
		for(int i = 0; i < jpgPaths.Length; i++)
		{
			if(!jpgPaths[i].EndsWith(".png") && !jpgPaths[i].EndsWith(".jpg"))
			{
				continue;
			}

			bool isAlpha = jpgPaths[i].EndsWith(".png");

			Dictionary<string, TempTextureFormat> dic = SetTextureReadable(jpgPaths[i]);
			Texture2D tex = AssetDatabase.LoadAssetAtPath(jpgPaths[i], typeof(Texture2D)) as Texture2D;

			int minY = 0;
			for(; minY < tex.height; minY++)
			{
				Color[] colors = tex.GetPixels(0, minY, tex.width, 1);
				int m = 0;
				for(;m < colors.Length; m++)
				{
					if(!colors[m].isSpace(isAlpha))
					{
						break;
					}
				}
				if(m < colors.Length)
				{
					break;
				}
			}

			int maxY = tex.height - 1;
			for(; maxY >= 0; maxY--)
			{
				Color[] colors = tex.GetPixels(0, maxY, tex.width, 1);
				int m = 0;
				for(;m < colors.Length; m++)
				{
					if(!colors[m].isSpace(isAlpha))
					{
						break;
					}
				}
				if(m < colors.Length)
				{
					break;
				}
			}
			maxY = tex.height - 1 - maxY;

			int minX = 0;
			for(; minX < tex.width; minX++)
			{
				Color[] colors = tex.GetPixels(minX, 0, 1, tex.height);
				int m = 0;
				for(;m < colors.Length; m++)
				{
					if(!colors[m].isSpace(isAlpha))
					{
						break;
					}
				}
				if(m < colors.Length)
				{
					break;
				}
			}

			int maxX = tex.width - 1;
			for(; maxX >= 0; maxX--)
			{
				Color[] colors = tex.GetPixels(maxX, 0, 1, tex.height);
				int m = 0;
				for(;m < colors.Length; m++)
				{
					if(!colors[m].isSpace(isAlpha))
					{
						break;
					}
				}
				if(m < colors.Length)
				{
					break;
				}
			}

			maxX = tex.width - 1 - maxX;


			if(isAlpha)
			{
				if(minX > 0 || minY > 0 || maxX  > 0 || maxY > 0)
				{
					Debug.LogError(jpgPaths[i] + " " + minX + " " + maxX + " " + minY + " " + maxY);
					Color[] colors = tex.GetPixels(minX, minY, tex.width - minX - maxX, tex.height - minY - maxY);
					Texture2D newTex = new Texture2D(tex.width - minX - maxX, tex.height - minY - maxY);
					newTex.SetPixels(colors);
					byte[] bytes = newTex.EncodeToJPG();
					string path = jpgPaths[i];
					path = path.Replace(srcPath, destPath);
					CommonUtil.bytesToFile(path, bytes);
				}
			}
			else
			{
				if(minX > 1 || minY > 1 || maxX  > 1 || maxY > 1)
				{
					Debug.LogError(jpgPaths[i] + " " + minX + " " + maxX + " " + minY + " " + maxY);
					Color[] colors = tex.GetPixels(minX, minY, tex.width - minX - maxX, tex.height - minY - maxY);
					Texture2D newTex = new Texture2D(tex.width - minX - maxX, tex.height - minY - maxY);
					newTex.SetPixels(colors);
					byte[] bytes = newTex.EncodeToJPG();
					string path = jpgPaths[i];
					path = path.Replace(srcPath, destPath);
					CommonUtil.bytesToFile(path, bytes);
				}
			}

			tex = null;
			ReverseTextureReadable(jpgPaths[i], dic);
		}

		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}

	[MenuItem("Assets/Custom/OldProject/checkAlpha")]
	public static void checkAlpha()
	{
		if(Selection.activeObject is Sprite)
		{
			Selection.activeObject = (Selection.activeObject as Sprite).texture;
		}

		if(Selection.activeObject is Texture2D)
		{
			Texture2D tex = Selection.activeObject as Texture2D;

			string texPath = AssetDatabase.GetAssetPath(tex);
			Dictionary<string,TempTextureFormat> temp = SetTextureReadable(texPath);

			int minAlpha = byte.MaxValue;
			int maxAlpha = byte.MinValue;
			Color32[] c = tex.GetPixels32();
			for(int i = 0; i < c.Length; i++)
			{
				int a = c[i].a;
				minAlpha = (byte)Mathf.Min(a, minAlpha);
				maxAlpha = (byte)Mathf.Max(a, maxAlpha);
			}

			ReverseTextureReadable(texPath, temp);
			Debug.Log(texPath + "  max_alpha:" + maxAlpha + " " + " min_alpha:" + minAlpha);
		}
		else
		{

		}
	}

	[MenuItem("Assets/Custom/OldProject/createAlphaTex")]
	public static void createAlphaTex()
	{
		if(Selection.activeObject is Sprite)
		{
			Selection.activeObject = (Selection.activeObject as Sprite).texture;
		}
		
		if(Selection.activeObject is Texture2D)
		{
			Texture2D tex = Selection.activeObject as Texture2D;
			
			string texPath = AssetDatabase.GetAssetPath(tex);
			Dictionary<string,TempTextureFormat> temp = SetTextureReadable(texPath);


			Color32[] c = tex.GetPixels32();
			for(int i = 0; i < c.Length; i++)
			{
				byte a = c[i].a;
				int t = ((int)a) * 50;
				if(t > 255)
				{
					a = 255;
				}
				else
				{
					a = (byte)t;
				}
				c[i].r = a;
				c[i].g = a;
				c[i].b = a;
				c[i].a = 255;
			}

			ReverseTextureReadable(texPath, temp);

			Texture2D newTex = new Texture2D(tex.width, tex.height, TextureFormat.RGB24, false);
			newTex.SetPixels32(c);
			byte[] data = newTex.EncodeToPNG();

			string fileName = Path.GetFileNameWithoutExtension(texPath);
			string ext = Path.GetExtension(texPath);
			string newPath = texPath.Replace(fileName + ext, fileName + "_alpha" + ext);
			CommonUtil.bytesToFile(newPath, data);

			AssetDatabase.Refresh();
		}
	}

	[MenuItem("Assets/Custom/OldProject/convertToJpg(MultiAlpha)")]
	public static void convertToJpg2()
	{
		for(int i = 0; i < Selection.assetGUIDs.Length; i++)
		{
			string texPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]);
			
			if(!texPath.EndsWith(".png"))
			{
				continue;
			}
			
			Dictionary<string,TempTextureFormat> temp = SetTextureReadable(texPath);
			Texture2D tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;
			Color[] color = tex.GetPixels();
			for(int j = 0; j < color.Length; j++)
			{
				Color c = color[j];
				c.r *= c.a;
				c.b *= c.a;
				c.g *= c.a;
				c.a = 1;
				color[j] = c;
			}
			tex.SetPixels(color);
			byte[] data = tex.EncodeToJPG();
			ReverseTextureReadable(texPath, temp);
			
			string newPath = texPath.Replace(".png", ".jpg");
			CommonUtil.bytesToFile(newPath, data);
			string oldMetaFilePath = texPath + ".meta";
			string newMetaFilePath = newPath + ".meta";
			CommonUtil.Move(oldMetaFilePath, newMetaFilePath);
			CommonUtil.Delete(texPath);
		}
		AssetDatabase.Refresh();
	}

	

	[MenuItem("Custom/OldProject/Prefab/CopyPlatformRes")]
	public static void CopyPlatformRes()
	{
		MovePlatformAnim2(ConfigTool.bundleDir[0]);
	}

	public static void MovePlatformAnim2(string resPath)
	{
		string[] exts = new string[]{"*.anim", "*.prefab", "*.mat"};
		string platformAnimPath = resPath + "/" + EditorCommonTool.getCopiedDirName(EditorUserBuildSettings.activeBuildTarget);
		if(!Directory.Exists(platformAnimPath))
		{
			return;
		}
		string animPath = resPath;

		for(int j = 0; j < exts.Length; j++)
		{
			string[] paths = Directory.GetFiles(platformAnimPath, exts[j], SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths[i];
				string destPath = path.Replace(platformAnimPath, animPath);
				CommonUtil.Copy(path, destPath);
			}
		}
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/Sprite/CheckSprite2")]
	public static void CheckSprite2()
	{
        string[] resPaths = ConfigTool.bundleDir;
		string[] exts = new string[]{"*.png", "*.jpg"};
		for(int i = 0; i < resPaths.Length; i++)
		{
			SpriteSheetConfig config = EditorCommonTool.getRawSpriteSheetConfig(resPaths[i]);

			for(int j = 0; j < exts.Length; j++)
			{
				string[] paths = Directory.GetFiles(resPaths[i], exts[j], SearchOption.AllDirectories);
				for(int k = 0; k < paths.Length; k++)
				{
					string path = paths[k];
					if(path.Contains("/" + Platform.ios + "/"))
					{
						continue;
					}
					if(path.Contains("/" + Platform.android + "/"))
					{
						continue;
					}

					path = path.Replace(resPaths[i] + "/", "");

					string spriteSheetName = config.getSpriteSheetName(path);
					if(spriteSheetName == null)
					{
						Debug.LogError("sprite not merge to sprite sheet:" + path);
					}
				}
			}
		}
	}


	[MenuItem("Custom/OldProject/Modify/ChangeSpriteModeToSingle")]
	static void CheckMaterial ()
	{
		string[] files = Directory.GetFiles(ConfigTool.bundleDir[0], "*.mat", SearchOption.AllDirectories);
		for(int i = 0; i < files.Length; i++)
		{
			Material mat = AssetDatabase.LoadAssetAtPath(files[i], typeof(Material)) as Material;
			Texture tex =  mat.mainTexture;
			if(tex == null)
			{
				Debug.LogError("main texture is null: " + files[i]);
			}
			else
			{
				string texPath = AssetDatabase.GetAssetPath(tex);
				TextureImporter importer = TextureImporter.GetAtPath(texPath) as TextureImporter;

				if(importer.spriteImportMode == SpriteImportMode.None)
				{
					Debug.LogError("not found sprite: " + texPath);
					importer.spriteImportMode = SpriteImportMode.Single;
					AssetDatabase.ImportAsset (texPath);
				}
			}

			string shaderName = mat.shader.name;
			if(shaderName != "Particles/Additive"
			   && shaderName != "Particles/Additive (Soft)"
			   && shaderName != "Particles/Alpha Blended")
			{
				Debug.LogError("error shader:" + shaderName + " | " + files[i]);
			}
		}
	}

	[MenuItem("Custom/OldProject/Modify/CheckPrefabBuiltinMaterial")]
	static void CheckPrefabBuiltinMaterial ()
	{
		Material mat = AssetDatabase.LoadAssetAtPath(ConfigTool.bundleDir[0] + "/common_material/default_particle.mat", typeof(Material)) as Material;
		if(mat == null)
		{
			return;
		}
		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths [i];
				Object realPrefab = AssetDatabase.LoadAssetAtPath (path, typeof(Object));
				if (realPrefab == null)
				{
					Debug.LogError ("InstantiatePrefab failed: " + path);
					continue;
				}
				
				GameObject prefab = realPrefab as GameObject;
				if (prefab == null)
				{
					Debug.LogError ("InstantiatePrefab failed 2: " + path);
					continue;
				}
				
				ParticleSystem[] renders = prefab.GetComponentsInChildren<ParticleSystem> (true);
				for (int j = 0; j < renders.Length; j++)
				{
					Renderer renderer = renders[j].GetComponent<Renderer>();
					if(renderer != null)
					{
						Material material = renderer.sharedMaterial;
						if(material != null)
						{
							if(material.name.Contains("Default-Particle"))
							{
								Debug.LogError ("CheckPrefab1: " + path);
								Debug.LogError ("CheckPrefab2: " + material.mainTexture.name);

								renderer.sharedMaterial = mat;

								EditorUtility.SetDirty(realPrefab);
							}
						}
					}	
				}
			}
		}

		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}


	[MenuItem("Custom/OldProject/Modify/CheckParticalAdditive")]
	static void CheckParticalAdditive ()
	{
		List<string> ls = new List<string>();
		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.mat", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths [i];
				Material realPrefab = AssetDatabase.LoadAssetAtPath (path, typeof(Material)) as Material;
				if (realPrefab == null)
				{
					Debug.LogError ("InstantiatePrefab failed: " + path);
					continue;
				}
				
				if(realPrefab.shader.name == "Particles/Additive")
				{
					ls.Add(path);
				}
			}
		}

		string str = "";
		ls.Sort();
		for(int i = 0; i < ls.Count; i++)
		{
			str += ls[i] + "\n";
		}

		Debug.Log(str);
	}

	[MenuItem("Custom/OldProject/Modify/CheckPrefabBuiltinSprite")]
	static void CheckPrefabBuiltinSprite ()
	{
		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths [i];
				Object realPrefab = AssetDatabase.LoadAssetAtPath (path, typeof(Object));
				if (realPrefab == null)
				{
					Debug.LogError ("InstantiatePrefab failed: " + path);
					continue;
				}
				
				GameObject prefab = realPrefab as GameObject;
				if (prefab == null)
				{
					Debug.LogError ("InstantiatePrefab failed 2: " + path);
					continue;
				}
				
				SpriteRenderer[] renders = prefab.GetComponentsInChildren<SpriteRenderer> (true);
				for (int j = 0; j < renders.Length; j++)
				{
					Sprite sprite = renders[j].sprite;
					if(sprite != null)
                    {
						string spritePath = AssetDatabase.GetAssetPath(sprite);
						if(spritePath.Contains("unity_builtin_extra"))
                        {
                            Debug.LogError ("CheckPrefab1: " + path);
                            Debug.LogError ("CheckPrefab2: " + sprite.texture.name);
							Debug.LogError ("CheckPrefab3: " + renders[j].gameObject.transform.parent.gameObject.name + "->" + renders[j].gameObject.name);
							Debug.LogError ("CheckPrefab4: " + spritePath);

							renders[j].sprite = null;
							EditorUtility.SetDirty(prefab);
                        }
                    }	
                }

				Image[] images = prefab.GetComponentsInChildren<Image> (true);
				for (int j = 0; j < images.Length; j++)
				{
					Sprite sprite = images[j].sprite;
					if(sprite != null)
					{
						string spritePath = AssetDatabase.GetAssetPath(sprite);
						if(spritePath.Contains("unity_builtin_extra"))
						{
							Debug.LogError ("CheckPrefab1: " + path);
							Debug.LogError ("CheckPrefab2: " + sprite.texture.name);
							Debug.LogError ("CheckPrefab3: " + images[j].gameObject.transform.parent.gameObject.name + "->" + images[j].gameObject.name);
							Debug.LogError ("CheckPrefab4: " + spritePath);

							images[j].sprite = null;
							EditorUtility.SetDirty(prefab);
                        }
                    }
                }
            }
        }
        
		AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

// 	[MenuItem("Custom/OldProject/Prefab/BuildCopy")]
// 	public static void BuildCopy()
// 	{
// 		BuildCopy2(ConfigTool.bundleDir[0]);
// 	}

	public static void BuildCopy2(string resPath, HashSet<string> hashSet = null)
	{
//		BuildTarget[] platforms = new BuildTarget[]{BuildTarget.Android};
//		BuildTarget[] platforms = new BuildTarget[]{EditorCommonTool.build_target_ios};
		BuildTarget[] platforms = new BuildTarget[]{BuildTarget.Android, EditorCommonTool.build_target_ios};

		if(hashSet == null)
		{
			hashSet = AutoBuildAnim.getBuildCopyConfig(resPath);
		}

		if(hashSet == null)
		{
			return;
		}

		string[] ext = new string[]{"*.anim", "*.mat", "*.prefab"};
		for(int u = 0; u < platforms.Length; u++)
		{
			BuildTarget target = platforms[u];
			HashSet<string> deleteSet = new HashSet<string>();
            foreach(string copyPath in hashSet)
			{
				string animPath = resPath + "/" + copyPath;
				string outputPath = resPath + "/" + target.getPlatform() + "/" + ResourcesEx.CopiedDirName + "/" + copyPath;

				string fileExt = Path.GetExtension(copyPath);
				if(string.IsNullOrEmpty(fileExt))
				{
					if(!Directory.Exists(animPath))
					{
						CommonUtil.Delete(outputPath);
						deleteSet.Add(copyPath);
						continue;
					}

					Directory.CreateDirectory(outputPath);

					for(int j = 0; j < ext.Length; j++)
					{
						string[] deletePaths = Directory.GetFiles(outputPath, ext[j], SearchOption.AllDirectories);
						for(int i = 0; i < deletePaths.Length; i++)
						{
							CommonUtil.Delete(deletePaths[i]);
						}
						
						string[] paths = Directory.GetFiles(animPath, ext[j], SearchOption.AllDirectories);
						for(int i = 0; i < paths.Length; i++)
                        {
                            string destPath = paths[i].Replace(animPath, outputPath);
                            string dir = Path.GetDirectoryName(destPath);
                            Directory.CreateDirectory(dir);
							CommonUtil.Copy(paths[i], destPath);
						}
					}
				}
				else
				{
					if(File.Exists(animPath))
					{
						string d = Path.GetDirectoryName(outputPath);
						Directory.CreateDirectory(d);
						CommonUtil.Copy(animPath, outputPath);
					}
					else
					{
						CommonUtil.Delete(outputPath);
						deleteSet.Add(copyPath);
					}
				}
			}

			AssetDatabase.Refresh();

			HashSet<string> newSet = new HashSet<string>(hashSet);
			foreach(string delP in deleteSet)
			{
				newSet.Remove(delP);
			}


			List<string> outputPaths = new List<string>();
			foreach(string copyPath in newSet)
			{
				string outputPath = resPath + "/" + target.getPlatform() + "/" + ResourcesEx.CopiedDirName + "/" + copyPath;
				outputPaths.Add(outputPath);
			}
			
			string[] prefabDirs = outputPaths.ToArray();
			setAnimReference (resPath, target, prefabDirs);
			SetMaterialReferenceToSpriteSheet2(resPath, target, prefabDirs);
            SetPrefabReferenceToSpriteSheet4(resPath, target, prefabDirs);
		}

	}

	public delegate void processReference(string resPath, BuildTarget target, string[] prefabDirs);

	public static void SetReferenceToSpriteSheet (processReference r)
	{
		Dictionary<string, string[]> dic = new Dictionary<string, string[]> ();
		dic.Add (ConfigTool.bundleDir[0], new string[] {
			"",
		});

		Dictionary<string, string[]>.Enumerator e = dic.GetEnumerator ();
		BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
		while (e.MoveNext ())
		{
			string resPath = e.Current.Key;
			if(!Directory.Exists(resPath))
			{
				continue;
			}
			List<string> outputPaths = new List<string> ();
			for (int i = 0; i < e.Current.Value.Length; i++) {
				string outputPath = resPath + "/" + e.Current.Value [i];
				outputPaths.Add (outputPath);
			}
			string[] prefabDirs = outputPaths.ToArray ();

			r(resPath, target, prefabDirs);

		}
	}

	[MenuItem("Custom/OldProject/Prefab/SetPrefabReferenceToSpriteSheet")]
	public static void SetPrefabReferenceToSpriteSheet ()
	{
		deleteNoNeedFiles();

		MaterialTextureForETC1.CreateMenuMaterial();
		MaterialTextureForETC1.CreateFootPrintMaterial();

		SetReferenceToSpriteSheet(MaterialTextureForETC1.setAnimReference);
		SetReferenceToSpriteSheet(MaterialTextureForETC1.SetMaterialReferenceToSpriteSheet2);
		SetReferenceToSpriteSheet(MaterialTextureForETC1.SetPrefabReferenceToSpriteSheet4);

	}

	[MenuItem("Custom/OldProject/Sprite/DeleteOldSpriteSheet")]
	public static void DeleteOldSpriteSheet()
	{
        return;
		string resPath = ConfigTool.bundleDir[0];
		BuildTarget[] targets = new BuildTarget[]{BuildTarget.Android, EditorCommonTool.build_target_ios};
		for(int i = 0; i < targets.Length; i++)
		{
			BuildTarget target = targets[i];

			HashSet<string> deleteSet = new HashSet<string>();
			SpriteSheetConfig rawConfig = EditorCommonTool.getRawSpriteSheetConfig(resPath);
			SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, target.getPlatform());
            if (config == null)
            {
                continue;
            }
			SpriteSheetConfig.Enumerator e = config.GetEnumerator();
			while(e.MoveNext())
			{
				if(e.Current.Value.isRoot())
				{
					if(!rawConfig.ContainsKey(e.Current.Key))
					{
						deleteSet.Add(e.Current.Key);
					}
				}
			}

			foreach(string deleteKey in deleteSet)
			{
				Dictionary<string, SpriteSheetInfo> map = new Dictionary<string, SpriteSheetInfo>();
				config.getSpriteSheetGroup(deleteKey, ref map);
				Dictionary<string, SpriteSheetInfo>.Enumerator e2 = map.GetEnumerator();
				while(e2.MoveNext())
				{
					if(e2.Current.Value.isLeaf())
					{
						CommonUtil.Delete(resPath + "/" + EditorCommonTool.getSheetDirName(target) + "/" + e2.Current.Key);
					}
					config.Remove(e2.Current.Key);
				}
			}

			EditorCommonTool.setSpriteSheetConfig(config, resPath, target.getPlatform());
			EditorCommonTool.setBinarySpriteSheetConfig(config, resPath, target.getPlatform());
		}
	}

	[MenuItem("Assets/Custom/OldProject/ParseAnimClip")]
	public static void ParseAnimClip()
	{
		AnimationClip clip = Selection.activeObject as AnimationClip;
        
        EditorCurveBinding[] curveBindings = AnimationUtility.GetObjectReferenceCurveBindings (clip);
		for (int j = 0; j < curveBindings.Length; j++)
		{
			Debug.Log("propertyName:" + curveBindings[j].propertyName);

			if (curveBindings [j].propertyName == "m_Material" || curveBindings [j].propertyName == "m_Materials.Array.data[0]")
			{
				ObjectReferenceKeyframe[] keyFrame = AnimationUtility.GetObjectReferenceCurve (clip, curveBindings [j]);
				for (int k = 0; k < keyFrame.Length; k++) {
					Material sprite = (Material)keyFrame [k].value;

					if(sprite != null)
					{
						Debug.Log("mat valid: " + sprite.name);
					}

//					if(sprite != null)
//					{
//						string spritePath = AssetDatabase.GetAssetPath (sprite);
//						string newSpriteName = spritePath.Replace (resPath + "/", "");
//						string spriteSheetName = spriteSheetConfig.getSpriteSheetName (newSpriteName);
//						string spriteSheetPath = "";
//						Sprite tempSprite = getSprite (resPath, ref spriteSheetMap, spriteSheetName, newSpriteName, ref spriteSheetPath, target);
//						if (tempSprite != null) {
//							isNeedSave = true;
//							keyFrame [k].value = tempSprite;
//						}
//						//								else
//                        //								{
//                        //									Debug.LogError("getSprite failed: " + spritePath);
//                        //								}
//                    }
                }
//                if (isNeedSave) {
//                    AnimationUtility.SetObjectReferenceCurve (clip, curveBindings [j], keyFrame);
//                }
            }
        }
    }

	private static int getEvony(string filePath, ref int index)
	{
		int evony = -1;
		const string evonyStr = "/Evony";
		index = filePath.IndexOf(evonyStr);
		
		if(index >= 0)
		{
			string temp = filePath.Substring(index + evonyStr.Length, 1);
			if(!int.TryParse(temp, out evony))
			{
				evony = -1;
			}
		}

		return evony;
	}


	private static int getAge(string filePath, ref int index)
	{
		int evony = -1;
		const string evonyStr = "/Age";
		index = filePath.IndexOf(evonyStr);
		
		if(index >= 0)
		{
			string temp = filePath.Substring(index + evonyStr.Length, 1);
			if(!int.TryParse(temp, out evony))
			{
				evony = -1;
			}
		}
		
		return evony;
	}

	[MenuItem("Custom/OldProject/Modify/CheckEvonyError")]
	public static void CheckEvonyError()
	{
		CommonUtil.stringToFile("error_evony.txt", "");

		bool checkEvonyPrefab = true;

		Dictionary<string, HashSet<string>> map = new Dictionary<string, HashSet<string>>();
		string[] files = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
		if(checkEvonyPrefab)
		{
			for(int i = 0; i < files.Length; i++)
			{
				string filePath = files[i];
				int index = 0;
				int evony = getEvony(filePath, ref index);
				if(evony < 0)
				{
					continue;
				}

				HashSet<string> set = null;
				map.TryGetValue(filePath, out set);
				try
				{
					string[] dependences = AssetDatabase.GetDependencies(new string[]{filePath});
					for(int j =  0; j < dependences.Length; j++)
					{
						string dependence = dependences[j];

						int index2 = 0;
						int evony2 = getEvony(dependence, ref index2);
						if(evony2 < 0)
						{
							continue;
						}

						try
						{
							if(evony2 != evony)
							{
								if(set == null)
								{
									set = new HashSet<string>();
									map.Add(filePath, set);
								}

								set.Add(dependence);
							}
						}
						catch(System.Exception)
						{
							continue;
						}
					}
				}
				catch(System.Exception)
				{
					continue;
				}
			}
		}

		for(int i = 0; i < files.Length; i++)
		{
			string filePath = files[i];

			int index = 0;
			int evony = getEvony(filePath, ref index);
			if(evony >= 0)
			{
				continue;
			}
			
			HashSet<string> set = null;
			map.TryGetValue(filePath, out set);

			string[] dependences = AssetDatabase.GetDependencies(new string[]{filePath});
			for(int j =  0; j < dependences.Length; j++)
			{
				string dependence = dependences[j];
				int index3 = 0;
				int evony2 = getEvony(dependence, ref index3);
				if(evony2 < 0)
				{
					continue;
				}

				try
				{
					if(set == null)
					{
						set = new HashSet<string>();
						map.Add(filePath, set);
					}
					
					set.Add(dependence);
				}
				catch(System.Exception)
                {
                    
                }
            }
        }

		SpriteSheetConfig spConfig = EditorCommonTool.getSpriteSheetConfig(ConfigTool.bundleDir[0]);
		BundleConfig config = EditorCommonTool.getBundleConfig();
		HashSet<string> testBundleNames = new HashSet<string>();
		config.getGroupBundles("city_evony1", ref testBundleNames);
		config.getGroupBundles("city_evony2", ref testBundleNames);
		config.getGroupBundles("city_evony3", ref testBundleNames);
		config.getGroupBundles("city_evony4", ref testBundleNames);
		config.getGroupBundles("city_evony5", ref testBundleNames);
		config.getGroupBundles("city_evony6", ref testBundleNames);


		SortedDictionary<string, HashSet<string>> tempMap = new SortedDictionary<string, HashSet<string>>(map);
		Dictionary<string, HashSet<string>>.Enumerator e = map.GetEnumerator();
		while(e.MoveNext())
		{
			HashSet<string> set = e.Current.Value;
			HashSet<string> tempSet = new HashSet<string>(set);

			foreach(string q in tempSet)
			{
				string p = q;
				if(p.Contains(ConfigTool.bundleDir[0] + "/"))
				{
					p = p.Replace(ConfigTool.bundleDir[0] + "/", "");
				}
				else
				{
					continue;
				}
				string spName = spConfig.getSpriteSheetName(p);

				if(!testBundleNames.Contains(spName))
				{
					set.Remove(q);
				}
			}

			if(set.Count <= 0)
			{
				tempMap.Remove(e.Current.Key);
			}
		}

		string str = JsonConvert.SerializeObject(tempMap, Newtonsoft.Json.Formatting.Indented);
		CommonUtil.stringToFile("error_evony.txt", str);

		HashSet<string> evonyDirs = new HashSet<string>();
		SortedDictionary<string, HashSet<string>>.Enumerator e2 = tempMap.GetEnumerator();
		while(e2.MoveNext())
		{
			foreach(string n in e2.Current.Value)
			{
				int index = 0;
				getEvony(n, ref index);
				evonyDirs.Add(n.Substring(0, index));
			}
		}

		string str2 = JsonConvert.SerializeObject(evonyDirs, Newtonsoft.Json.Formatting.Indented);
		CommonUtil.stringToFile("error_evony2.txt", str2);
    }


	[MenuItem("Custom/OldProject/Modify/CheckAgeError")]
	public static void CheckAgeError()
	{
		CommonUtil.stringToFile("error_age.txt", "");
		
		bool checkEvonyPrefab = true;

		Dictionary<string, string> resMap = getAllResGuidMap("Assets");

		Dictionary<string, HashSet<string>> map = new Dictionary<string, HashSet<string>>();
		string[] files = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
		if(checkEvonyPrefab)
		{
			for(int i = 0; i < files.Length; i++)
			{
				string filePath = files[i];
				int index = 0;
				int evony = getAge(filePath, ref index);
				if(evony < 0)
				{
					continue;
				}
				
				HashSet<string> set = null;
				map.TryGetValue(filePath, out set);
				try
				{
					HashSet<string> guids = getDependenceGuids(filePath);
					foreach(string guid in guids)
					{
						string dependence = null;
						resMap.TryGetValue(guid, out dependence);
						if(dependence == null)
						{
							continue;
						}

						int index2 = 0;
						int evony2 = getAge(dependence, ref index2);
						if(evony2 < 0)
						{
							continue;
						}
						
						try
						{
							if(evony2 != evony)
							{
								if(set == null)
								{
									set = new HashSet<string>();
									map.Add(filePath, set);
								}
								
								set.Add(dependence);
							}
						}
						catch(System.Exception)
						{
							continue;
						}
					}
				}
				catch(System.Exception)
				{
					continue;
				}
			}
		}
		
		for(int i = 0; i < files.Length; i++)
		{
			string filePath = files[i];
			
			int index = 0;
			int evony = getAge(filePath, ref index);
			if(evony >= 0)
			{
				continue;
			}
			
			HashSet<string> set = null;
			map.TryGetValue(filePath, out set);

			HashSet<string> guids = getDependenceGuids(filePath);

			foreach(string guid in guids)
			{
				string dependence = null;
				resMap.TryGetValue(guid, out dependence);
				if(dependence == null)
				{
					continue;
				}

				int index3 = 0;
				int evony2 = getAge(dependence, ref index3);
				if(evony2 < 0)
				{
					continue;
				}
				
				try
				{
					if(set == null)
					{
						set = new HashSet<string>();
						map.Add(filePath, set);
					}
					
					set.Add(dependence);
				}
				catch(System.Exception)
				{
					
				}
			}
		}
		
		SpriteSheetConfig spConfig = EditorCommonTool.getSpriteSheetConfig(ConfigTool.bundleDir[0]);
		BundleConfig config = EditorCommonTool.getBundleConfig();
		HashSet<string> testBundleNames = new HashSet<string>();
		config.getGroupBundles("delete", ref testBundleNames);
		
		
		SortedDictionary<string, HashSet<string>> tempMap = new SortedDictionary<string, HashSet<string>>(map);
		Dictionary<string, HashSet<string>>.Enumerator e = map.GetEnumerator();
		while(e.MoveNext())
		{
			HashSet<string> set = e.Current.Value;
			HashSet<string> tempSet = new HashSet<string>(set);
			
			foreach(string q in tempSet)
			{
				string p = q;
				if(p.Contains(ConfigTool.bundleDir[0] + "/"))
				{
					p = p.Replace(ConfigTool.bundleDir[0] + "/", "");
				}
				else
				{
					continue;
				}
				string spName = spConfig.getSpriteSheetName(p);
				
				if(!testBundleNames.Contains(spName))
				{
					set.Remove(q);
				}
			}
			
			if(set.Count <= 0)
			{
				tempMap.Remove(e.Current.Key);
			}
		}



		SortedDictionary<string, List<string>> map2 = new SortedDictionary<string, List<string>>();
		SortedDictionary<string, HashSet<string>>.Enumerator en = tempMap.GetEnumerator();
		while(en.MoveNext())
		{
			List<string> ls = new List<string>(en.Current.Value);
			ls.Sort();
			map2.Add(en.Current.Key, ls);
		}

		string str = JsonConvert.SerializeObject(map2, Newtonsoft.Json.Formatting.Indented);
		CommonUtil.stringToFile("error_age.txt", str);
	}


	[MenuItem("Custom/OldProject/Modify/SetAllPrefabDirty")]
	public static void SetAllPrefabDirty()
	{
		string[] files = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);

		for(int i = 0; i < files.Length; i++)
		{
			string filePath = files[i];
			Object prefab = AssetDatabase.LoadAssetAtPath(filePath, typeof(Object));
			EditorUtility.SetDirty(prefab);
		}

		AssetDatabase.SaveAssets();
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/PrintAllPath")]
	public static void PrintAllPath()
	{
		Debug.Log(Application.persistentDataPath);
		Debug.Log(Application.streamingAssetsPath);
		Debug.Log(Application.dataPath);
		Debug.Log(Application.temporaryCachePath);
	}

	[MenuItem("Custom/OldProject/Modify/CheckSpriteNotInSpriteSheet")]
	public static void CheckSpriteNotInSpriteSheet()
	{
		//		string outputFileName = "error_sprite.txt";
		//
		//		CommonUtil.Delete(outputFileName);
		//
		//		string[] resPaths = new string[]{CreateSpriteSheet.bundleDir, CreateSpriteSheet.localBundleDir};
		//		for(int i = 0; i < resPaths.Length; i++)
		//		{
		//			string resPath = resPaths[i];
		//
		//			File.AppendAllText(outputFileName, "" + resPath + ":\n");
		//
		//			SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath);
		//
		//			string[] exts = new string[]{"*.jpg", "*.png"};
		//			List<string> l = new List<string>();
		//			for(int k = 0; k < exts.Length; k++)
		//			{
		//				string[] filePaths = Directory.GetFiles(resPath, exts[k], SearchOption.AllDirectories);
		//				for(int j = 0; j < filePaths.Length; j++)
		//				{
		//					string filePath = filePaths[j];
		//					if(filePath.Contains("/" + ResourcesEx.SheetDirName + "/"))
		//					{
		//						continue;
		//					}
		//
		//					string filePath2 = filePath.Replace(resPath + "/", "");
		//
		//					string spriteSheetName = config.getSpriteSheetName(filePath2);
		//					if(spriteSheetName == null)
		//					{
		//						l.Add(filePath);
		//					}
		//				}
		//			}
		//
		//			l.Sort();
		//			for(int k = 0; k < l.Count; k++)
		//			{
		//				File.AppendAllText(outputFileName, "\t" + l[k] + "\n");
		//			}
		//		}
		
		string outputFileName = "error_sprite.txt";
		
		CommonUtil.Delete(outputFileName);
		
		string str = "";

		List<string> l = new List<string>();

        string[] resPaths = ConfigTool.bundleDir;
		for(int i = 0; i < resPaths.Length; i++)
		{
			string resPath = resPaths[i];
			
			Dictionary<KeyValuePair<string, string>, SpriteIdInfo> idMap = getSpriteIdInfoMap(resPath, EditorUserBuildSettings.activeBuildTarget);
			
			string[] exts = new string[]{"*.jpg", "*.png"};

			for(int k = 0; k < exts.Length; k++)
			{
				string[] filePaths = Directory.GetFiles(resPath, exts[k], SearchOption.AllDirectories);
				for(int j = 0; j < filePaths.Length; j++)
				{
					string filePath = filePaths[j];
					if(filePath.Contains("/" + ResourcesEx.SheetDirName + "/"))
					{
						continue;
					}
					
					string texGuid = null;
					Dictionary<string, string> idMap2 = new Dictionary<string, string>();
					Dictionary<string, string> idMap3 = getSpriteIdInfoMap3(filePath, ref idMap2, ref texGuid);
					
					Dictionary<string, string>.Enumerator enumerator = idMap3.GetEnumerator();
					while(enumerator.MoveNext())
					{
						if(!idMap.ContainsKey(new KeyValuePair<string, string>(enumerator.Current.Key, texGuid)))
						{
							l.Add(filePath + " | " + enumerator.Current.Key + " | " + enumerator.Current.Value);
						}
					}
				}
			}
		}

		l.Sort();
		for(int k = 0; k < l.Count; k++)
		{
			File.AppendAllText(outputFileName, "\t" + l[k] + "\n");
		}
	}

	[MenuItem("Custom/OldProject/Modify/CheckPrefabErrorResReference")]
	public static Dictionary<string, HashSet<string>> CheckPrefabErrorResReference()
	{
		Dictionary<string, HashSet<string>> map = new Dictionary<string, HashSet<string>>();
		Dictionary<string, string> resMap = getAllResGuidMap("Assets");

		string[] resPaths = ConfigTool.bundleDir;
		for(int i = 0; i < resPaths.Length; i++)
		{
			string resPath = resPaths[i];

			string[] paths = Directory.GetFiles(resPath, "*.prefab", SearchOption.AllDirectories);
			for(int j = 0; j < paths.Length; j++)
			{
				string path = paths[j];

				HashSet<string> idMap = getDependenceGuids(path);
				foreach(string id in idMap)
				{
					string dp = null;
					if(resMap.TryGetValue(id, out dp))
					{
						if(!dp.EndsWith(".cs") && !dp.StartsWith(resPath))
						{
							HashSet<string> s = null;
							if(!map.TryGetValue(path, out s))
							{
								s = new HashSet<string>();
								map.Add(path, s);
							}

							s.Add(dp);
						}
					}
					else
					{
//						File.AppendAllText(outputFileName, "\t\tnot found res:" + id + "\n");
					}
				}
			}
		}

		return map;
	}

	[MenuItem("Custom/OldProject/Modify/CheckResName")]
	public static void CheckResName()
	{	
		string str = "";
        string[] resPaths = new string[]{ResourcesEx.BundleResDir + "/"};
		for(int i = 0; i < resPaths.Length; i++)
		{	
			string resPath = resPaths[i];

			string[] filePaths = Directory.GetFiles(resPath, "*", SearchOption.AllDirectories);
			for(int j = 0; j < filePaths.Length; j++)
			{
				string filePath = filePaths[j];
				if(filePath.Contains(" "))
				{
					str += filePath + "\n";
					if(File.Exists(filePath))
					{
//						string newName = Path.GetFileName(filePath).Replace(" ", "");
//						string newPath = Path.GetDirectoryName(filePath) + "/" + newName;
//						File.Move(filePath, newPath);
					}
				}
			}
		}

		if(str.Length > 0)
		{
			Debug.LogError(str);
		}
	}

	[MenuItem("Custom/OldProject/Modify/CheckPrefabFlare")]
	public static void CheckPrefabFlare()
	{
		string[] prefabDirs = new string[]{"Assets/"};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.prefab", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths[i];

            	GameObject p = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
				GameObject q = GameObject.Instantiate(p) as GameObject;
				LensFlare[] flare = q.GetComponentsInChildren<LensFlare>();
				if(flare != null && flare.Length > 0)
				{
					Debug.LogError(path);
				}
				GameObject.DestroyImmediate(q);
			}
		}
	}

	[MenuItem("Custom/OldProject/Modify/FindRepeatModeSprite")]
	public static void FindRepeatModeSprite()
	{
		Debug.LogError((int)TextureWrapMode.Clamp + " " + (int)TextureWrapMode.Repeat);
        string[] prefabDirs = new string[]{ResourcesEx.BundleResDir};
		for(int v = 0; v < prefabDirs.Length; v++)
		{
			string[] paths = Directory.GetFiles(prefabDirs[v], "*.jpg", SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths[i];
				TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
				if(textureImporter.wrapMode != TextureWrapMode.Clamp)
				{
					Debug.LogError(textureImporter.wrapMode + ":" + path);
					textureImporter.wrapMode = TextureWrapMode.Clamp;
					AssetDatabase.ImportAsset(path);
				}
			}
			
		}
		
		AssetDatabase.SaveAssets();
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/Modify/CheckSameNameTex")]
	public static HashSet<string> CheckSameNameTex()
	{
		HashSet<string> set = new HashSet<string>();
		string[] fs = Directory.GetFiles("Assets/", "*.jpg", SearchOption.AllDirectories);
		for(int i = 0; i < fs.Length; i++)
		{
			string p = fs[i];
			string q = p.Replace(".jpg", ".png");
			if(File.Exists(q))
			{
				set.Add(p);
			}
		}

		return set;
	}

	[MenuItem("Custom/OldProject/Modify/CheckSpaceNameTex")]
	public static HashSet<string> CheckSpaceNameTex()
	{
		HashSet<string> set = new HashSet<string>();

		for(int j = 0; j < exts.Length; j++)
		{
            string[] fs = Directory.GetFiles(ResourcesEx.BundleResDir + "/", "*" + exts[j], SearchOption.AllDirectories);
			for(int i = 0; i < fs.Length; i++)
			{
				string p = fs[i];
				if(p.Contains(" "))
				{
					set.Add(p);
				}
			}
		}
		
		return set;
	}


//	[MenuItem("Custom/OldProject/Modify/CheckConfigResPath")]
//	public static void CheckConfigResPath()
//	{
//		string[] exts = new string[]{".png", ".jpg"};
//
//		HashSet<string> set = new HashSet<string>();
//		string[] resPaths = new string[]{CreateSpriteSheet.bundleDir, CreateSpriteSheet.localBundleDir};
//		Dictionary<int, UniformResourceConfigure> uniformResConfig = ConfigureManager.instance.ParseProtoConfigContent2<Dictionary<int, UniformResourceConfigure>>("UniformResourceConfigure");
//		Dictionary<int, UniformResourceConfigure>.ValueCollection values = uniformResConfig.Values;
//		foreach(UniformResourceConfigure config in values)
//		{
//			string s = config.path;
//			string dir = Path.GetDirectoryName(s);
//			string fileName = Path.GetFileName(s);
//			bool found = false;
//
//			if(!s.Contains("UIInterface"))
//			{
//				for(int i = 0; i < resPaths.Length; i++)
//				{
//					string d = resPaths[i] + "/" + dir;
//					try
//					{
//						if(Directory.Exists(d))
//						{
//							string[] p = Directory.GetFiles(d, fileName + ".*", SearchOption.TopDirectoryOnly);
//							if(p.Length > 0)
//							{
//								found = true;
//								break;
//							}
//						}
//					}
//					catch(System.Exception e)
//					{
//	//					Debug.LogException(e);
//					}
//
//					try
//					{
//						string dir2 = Path.GetDirectoryName(dir);
//						string fileName2 = Path.GetFileName(dir);
//						string d2 = resPaths[i] + "/" + dir2;
//
//						if(Directory.Exists(d2))
//						{
//							for(int j = 0; j < exts.Length; j++)
//							{
//								string[] p2 = Directory.GetFiles(d2, fileName2 + exts[j], SearchOption.TopDirectoryOnly);
//								if(p2.Length > 0)
//								{
//									Object[] objs = AssetDatabase.LoadAllAssetsAtPath(p2[0]);
//									for(int k = 0; k < objs.Length; k++)
//									{
//										if(objs[k] is Sprite)
//										{
//											if(objs[k].name == fileName)
//											{
//												found = true;
//												break;
//											}
//										}
//									}
//
//									if(found)
//									{
//										break;
//									}
//								}
//							}
//
//							if(found)
//							{
//								break;
//							}
//						}
//					}
//					catch(System.Exception e)
//					{
//	//					Debug.LogException(e);
//					}
//				}
//			}
//
//			if(!found)
//			{
////				Debug.LogError("error path:" + s);
//				set.Add(s);
//			}
//		}
//
//		string str = "";
//		foreach(string se in set)
//		{
//			str += se + "\n";
//		}
//		Debug.LogError(str);
//	}
	
	public static HashSet<string> GetAllCodeDirs()
	{
		HashSet<string> dirs = new HashSet<string>();
		string[] paths = Directory.GetFiles("Assets", "*.prefab", SearchOption.AllDirectories);
		string[] dependences = AssetDatabase.GetDependencies(paths);
		for(int i = 0; i < dependences.Length; i++)
		{
			string p = dependences[i];
			if(p.EndsWith(".cs"))
			{
				string dir = Path.GetDirectoryName(p);
				HashSet<string> delSet = new HashSet<string>();
				bool needAdd = true;
				foreach(string d in dirs)
				{
					if(d.Length > dir.Length)
					{
						if(d.Contains(dir) && d[dir.Length] == '/')
						{
							delSet.Add(d);
						}
					}
					else if(d.Length < dir.Length)
					{
						if(dir.Contains(d) && dir[d.Length] == '/')
						{
							needAdd = false;
							break;
						}
					}
				}

				if(needAdd)
				{
					dirs.Add(dir);
				}

				foreach(string delDir in delSet)
				{
					dirs.Remove(delDir);
				}
			}
		}

		return dirs;
	}

//	[MenuItem("Assets/Custom/OldProject/CreateIcpResource")]
//	public static void CreateIcpResource()
//	{
//		string[] resPaths = CreateSpriteSheet.bundleDir;
//		for(int i = 0; i < Selection.assetGUIDs.Length; i++)
//		{
//			string texPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]);
//
//			for(int j = 0; j < resPaths.Length; j++)
//			{
//				string resPath = resPaths[j];
//				if(texPath.StartsWith(resPath))
//				{
//					string destPath = texPath.Replace(resPath + "/", "");
//					Directory.CreateDirectory(resPath + "/" + ResourcesEx.IcpResDirName);
//					destPath = resPath + "/" + ResourcesEx.IcpResDirName + "/" + destPath.Replace('/', ResourcesEx.dirSymbol);
//					AssetDatabase.CopyAsset(texPath, destPath);
//					break;
//				}
//			}
//		}
//
//		AssetDatabase.Refresh();
//	}
//
//	[MenuItem("Custom/OldProject/Prefab/ReferenceToIcpResource")]
//	public static void ReferenceToIcpResource()
//	{
//		return;
//
//		if(SwitchConfig.icp != 1)
//		{
//			return;
//		}
//
//		string[] exts = new string[]{".meta"};
//		string[] resPaths = CreateSpriteSheet.bundleDir;
//		for(int j = 0; j < resPaths.Length; j++)
//		{
//			string resPath = resPaths[j];
//			string icpResPath = resPath + "/" + ResourcesEx.IcpResDirName;
//
//			for(int i = 0; i < exts.Length; i++)
//			{
//				string[] paths = Directory.GetFiles(icpResPath, "*" + exts[i], SearchOption.TopDirectoryOnly);
//				for(int k = 0; k < paths.Length; k++)
//				{
//					string path = paths[k];
//					string srcPath = path.Replace(ResourcesEx.IcpResDirName + "/", "");
//					srcPath = srcPath.Replace(ResourcesEx.dirSymbol, '/');
//
//					if(SwitchConfig.icp == 1)
//					{
//						if(File.Exists(srcPath))
//						{
//							string tempPath = path + ".temp";
//							CommonUtil.Move(path, tempPath);
//							CommonUtil.Move(srcPath, path);
//							CommonUtil.Move(tempPath, srcPath);
//						}
//					}
//					else
//					{
//						if(File.Exists(srcPath))
//						{
//							CommonUtil.Delete(path.Replace(".meta", ""));
//							CommonUtil.Delete(path);
//						}
//					}
//				}
//			}
//		}
//		
//		AssetDatabase.Refresh();
//	}


	[MenuItem("Custom/OldProject/Prefab/RepleacePrefabRes")]
	public static void RepleacePrefabRes()
	{
		string guid0 = "74ce97f38974c4ce8a563660b71d0288";
		string guid1 = "300d997b6a70f41848c7e4e95159852c";

		string[] paths = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			string str = CommonUtil.fileToString(path);
			string newStr = str.Replace(guid0, guid1);
			if(str != newStr)
			{
				CommonUtil.stringToFile(path, newStr);
			}
		}
		
		AssetDatabase.Refresh();
	}

	[MenuItem("Assets/Custom/OldProject/PrintGuid")]
	public static void PrintGuid()
	{
		string path = null;
		if(Selection.activeGameObject != null)
		{
			path = AssetDatabase.GetAssetPath(Selection.activeGameObject);
		}
		else
		{
			path = AssetDatabase.GetAssetPath(Selection.activeObject);
		}

		string guid = AssetDatabase.AssetPathToGUID(path);
		Debug.Log(path + ":\n" + guid);
	}

	[MenuItem("Custom/OldProject/WriteSwitchConfigFile")]
	public static void WriteSwitchConfigFile()
	{
		string str = JsonConvert.SerializeObject(new SwitchConfigInfo(), Newtonsoft.Json.Formatting.Indented);
		CommonUtil.stringToFile("Assets/StreamingAssets/switch_config.txt", str);
		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/OldProject/getSet")]
	public static void getSet()
	{
		SpriteSheetConfig config = EditorCommonTool.getRawSpriteSheetConfig(ConfigTool.bundleDir[0]);
		HashSet<string> hashSet = new HashSet<string>(config.Keys);
		string str = JsonConvert.SerializeObject(hashSet, Newtonsoft.Json.Formatting.Indented);
		Debug.Log(str);
	}
	
	[MenuItem("Custom/OldProject/Prefab/PrintPrefabReference")]
	public static void PrintPrefabReference()
	{
		Dictionary<string, string[]> map = new Dictionary<string, string[]>();
		Dictionary<string, HashSet<string>> map2 = new Dictionary<string, HashSet<string>>();

		string[] paths = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			string[] ds = AssetDatabase.GetDependencies(new string[]{path});

			map.Add(path, ds);
		}

		Dictionary<string, string[]>.Enumerator e = map.GetEnumerator();
		while(e.MoveNext())
		{
			string p = e.Current.Key;
			HashSet<string> dset = new HashSet<string>();
			Dictionary<string, string[]>.Enumerator e2 = map.GetEnumerator();
			while(e2.MoveNext())
			{
				string[] ds = e2.Current.Value;
				for(int j = 0; j < ds.Length; j++)
				{
					string d = ds[j];

					if(p == d)
					{
						dset.Add(e2.Current.Key);
					}
				}
			}

			map2.Add(p, dset);
		}


	}

	[MenuItem("Assets/Custom/OldProject/CopyAsset")]
	public static void CopyAsset()
	{
		string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
		string newAssetPath = CommonUtil.addSuffixToFileName(assetPath, "_copy");
		AssetDatabase.CopyAsset(assetPath, newAssetPath);
		AssetDatabase.Refresh();
	}

	[MenuItem("Assets/Custom/OldProject/ScaleTex")]
	public static void ScaleTex()
	{
		float scale = 0.5f;

		string p = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);

		string[] paths = null;
		if(Directory.Exists(p))
		{
			paths = Directory.GetFiles(p, "*", SearchOption.TopDirectoryOnly);
		}
		else
		{
			paths = new string[]{p};
		}

		for(int j = 0; j < paths.Length; j++)
		{
			string texPath = paths[j];
			if(!texPath.EndsWith("jpg") && !texPath.EndsWith("png"))
			{
				continue;
			}

			string ext = Path.GetExtension(texPath);

			Dictionary<string, TempTextureFormat> dic = SetTextureReadable(texPath);

			Texture2D tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;
			TextureImporter textureImporter = AssetImporter.GetAtPath (texPath) as TextureImporter;
			Vector4 border = textureImporter.spriteBorder;

			int tw =  tex.width;
			int th =  tex.height;

			Color32[] data = tex.GetPixels32();
			int e = data.Length;
			Resources.UnloadAsset(tex);
			ReverseTextureReadable(texPath, dic);

			int newTw = Mathf.RoundToInt(tw * scale);
			int newTh = Mathf.RoundToInt(th * scale);

			float densityx = (float)tw / newTw;
			float densityy = (float)th / newTh;
			Color32[] newPixel = new Color32[newTw * newTh];

			for(int u = 0; u < newTh; u++)
			{
				for(int v = 0; v < newTw; v++)
				{
					float le = v * densityx;
					float ri = le + densityx;
					float bo = u * densityy;
					float to = bo + densityy;




					int sumr = 0;
					int sumg = 0;
					int sumb = 0;
					int suma = 0;


					for(int b = (int)bo; b < to; b++)
					{
						for(int l = (int)le; l < ri; l++)
						{
							float fx = Mathf.Min(ri - l, 1);
							if(l <= le && Mathf.Abs(l - le) < fx)
							{
								fx = 1 - Mathf.Abs(l - le);
							}

							float fy = Mathf.Min(to - b, 1);
							if(b <= bo && Mathf.Abs(b - bo) < fy)
							{
								fy = 1 - Mathf.Abs(b - bo);
							}

							Color32 temp = data[l + b * tw];
							sumr += Mathf.RoundToInt(fx * fy * temp.r);
							sumg += Mathf.RoundToInt(fx * fy * temp.g);
							sumb += Mathf.RoundToInt(fx * fy * temp.b);
							suma += Mathf.RoundToInt(fx * fy * temp.a);
						}
					}

					float factor = densityx * densityy;
					byte nr = (byte)Mathf.RoundToInt(sumr / factor);
					byte ng = (byte)Mathf.RoundToInt(sumg / factor);
					byte nb = (byte)Mathf.RoundToInt(sumb / factor);
					byte na = (byte)Mathf.RoundToInt(suma / factor);
					newPixel[u * newTw + v] = new Color32(nr, ng, nb, na);
				}
			}

			TextureFormat format = TextureFormat.RGBA32;
			if(ext == ".jpg")
			{
				format = TextureFormat.RGB24;
			}

			Texture2D newTex = new Texture2D(newTw, newTh, format, false);
			newTex.SetPixels32(newPixel);
			byte[] newData = null;
			if(ext == ".png")
			{
				newData = newTex.EncodeToPNG();
			}
			else
			{
				newData = newTex.EncodeToJPG();
			}

			GameObject.DestroyImmediate(newTex);

			
//			CommonUtil.bytesToFile(CommonUtil.addSuffixToFileName(texPath, "_test"), newData);

			CommonUtil.bytesToFile(texPath, newData);
			border.x = Mathf.RoundToInt(border.x * ((float)newTw / tw));
			border.z = Mathf.RoundToInt(border.z * ((float)newTw / tw));
			border.y = Mathf.RoundToInt(border.y * ((float)newTh / th));
			border.w = Mathf.RoundToInt(border.w * ((float)newTh / th));
			textureImporter = AssetImporter.GetAtPath (texPath) as TextureImporter;
			textureImporter.spriteBorder = border;
		}

		AssetDatabase.Refresh();
	}
		

	[MenuItem("Custom/OldProject/SetSpriteSheetScale")]
	public static void SetSpriteSheetScale()
	{
		float scale = 0.5f;

		string[] arr = new string[]{
		"RoleModel_evony1",
		"RoleModel_evony2",
		"RoleModel_evony3",
		"RoleModel_evony4",
		"RoleModel_evony5",
		"RoleModel_evony6",
		"LangIcons",
		"TitleIcon",
		"GiftIcon",
		"RoleGiftIcon",

		"Task",
		"Tech",
		"Item",
		"BuffIcon",
		"PositionIcon",
		"GearIcon",
		"UIMenuIcon",
		"RoleIcon",
		"UICommon",
		"Mail",
		"NpcArt",
		"Guide",
		"NpcModel",
		"UIBest",

		"Flags",
		"GuildFlag",
		"UIAgeIcon",
		"UIBaseIcon",
		"UICityIcon",
		"UIEquipIcon",
		"UIGeneralCard",
		"UIGuildIcon",
		"UIRomeNum",
		"UIStoreIcon",
		"InspectIcon",
		"UITextUPgrade",
		"GeneralIcon",
		"GeneralModel"};

		SpriteSheetConfig config2 = EditorCommonTool.getRawSpriteSheetConfig(ConfigTool.bundleDir[0]);
		for(int i = 0; i < arr.Length; i++)
		{
			SpriteSheetInfo info2 = null;
			config2.TryGetValue(arr[i], out info2);
			info2.scale = scale;
		}

		EditorCommonTool.setRawSpriteSheetConfig(config2, ConfigTool.bundleDir[0]);
	}

	public static void deleteNoNeedFiles()
	{
        string[] paths = Directory.GetFiles(ResourcesEx.BundleResDir + "/", "*.FBX", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string dir = Path.GetDirectoryName(paths[i]);
			dir += "/" + "Materials";
			CommonUtil.Delete(dir);
		}
	}

	[MenuItem("Custom/OldProject/checkAsyncSprite")]
	public static void checkAsyncSprite()
	{
		string fileName = "async_load_sprite.txt";

		CommonUtil.Delete(fileName);

		string str = "";
		string[] paths = Directory.GetFiles("Assets", "*.prefab", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			Object realPrefab = AssetDatabase.LoadAssetAtPath(paths[i], typeof(Object));
			GameObject prefab = PrefabUtility.InstantiatePrefab(realPrefab) as GameObject;

			bool add = false;
			AsyncSpriteLoader[] loader = prefab.GetComponentsInChildren<AsyncSpriteLoader>();
			for(int j = 0; j < loader.Length; j++)
			{
				string p = loader[j].sprite_path;
				if(!add)
				{
					add = true;
					str += paths[i] + "\n";
				}
				str += p + "\n";
			}
			GameObject.DestroyImmediate(prefab);
		}

		CommonUtil.stringToFile(fileName, str);
	}

	[MenuItem("Custom/OldProject/checkVersionConfigSize")]
	public static void checkVersionConfigSize()
	{
		string l = "";
		uint newSize = 0;
		uint newSize1 = 0;
		uint newSize2 = 0;
		string str = CommonUtil.fileToString(Application.streamingAssetsPath + "/" + BundleVersionManager.configName);
		BundleVersionConfig config = BundleDownloadManager.ConvertToBundleVersionConfig(str);
		Dictionary<string, BundleInfo>.Enumerator e = config.bundles.GetEnumerator();
		while(e.MoveNext())
		{
			uint oSize = e.Current.Value.origin_size;
			uint size = e.Current.Value.size;
			if(size >= oSize * 0.9f)
			{
				l += ((float)size / oSize) + " " + size + " " + oSize + " " + e.Current.Key  + "\n";
				newSize += oSize - size;
				newSize1 += oSize;
				newSize2 += size;
			}
		}
		
		l = newSize + " " + newSize1 + " " + newSize2 + "\n" + l;
		Debug.LogError(l);
	}

	[MenuItem("Custom/OldProject/checkVersionConfigSize2")]
	public static void checkVersionConfigSize2()
	{
		string[] groups = new string[]{"evony1", "evony2", "evony3", "evony4", "evony5", "evony6", 
			"total_base", 
			"city_evony1", "city_evony2", "city_evony3", "city_evony4", "city_evony5", "city_evony6", "ui"};
		string[] groupDisplayName = new string[]{"文明1所有资源", "文明2所有资源", "文明3所有资源", "文明4所有资源", "文明5所有资源", "文明6所有资源",
			"公共资源", 
			"文明1独立资源", "文明2独立资源", "文明3独立资源", "文明4独立资源", "文明5独立资源", "文明6独立资源", "ui"};

		string str = CommonUtil.fileToString(Application.streamingAssetsPath + "/" + BundleVersionManager.configName);
		BundleVersionConfig config = BundleDownloadManager.ConvertToBundleVersionConfig(str);
		Platform platform = (Platform)System.Enum.Parse(typeof(Platform), config.platform);
		BundleConfig bundleConfig = EditorCommonTool.getBundleConfig(platform);

		string str2 = platform + ":\n";
		for(int i = 0; i < groups.Length; i++)
		{
			uint size0 = 0;
			uint size1 = 0;

			string groupName = groups[i];
			string displayGroupName = groupDisplayName[i];
			HashSet<string> set = new HashSet<string>();
			bundleConfig.getGroupBundles(groupName, ref set);
			foreach(string b in set)
			{

				BundleInfo info = null;
				if(config.bundles.TryGetValue(b, out info))
				{
					size0 += info.origin_size;
					size1 += info.size;
				}
			}

			str2 += displayGroupName + "  压缩后:" + CommonUtil.toSizeString(size1) + " 原大小:" + CommonUtil.toSizeString(size0) + "\n";
		}

		

		Debug.LogError(str2);
	}

//	[MenuItem("Custom/OldProject/Check")]
//	public static void check()
//	{
////		string path = EditorCommonTool.getBinarySpriteSheetConfigPath(CreateSpriteSheet.bundleDir, Platform.android);
////		TextAsset asset = AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)) as TextAsset;
////		SpriteSheetConfig config = new SpriteSheetConfig();
////		MemoryStream stream = new MemoryStream(asset.bytes);
////		BinaryReader reader = new BinaryReader(stream);
////		config.Read(reader);
//
//		AssetBundle bundle = BundleManager.CreateFromFile(Application.streamingAssetsPath + "/sprite_sheet_config+3340668985.unity3d");
//		Object[] r = BundleManager.LoadAll(bundle, typeof(TextAsset));
//		for(int i = 0; i < r.Length; i++)
//		{
//			TextAsset asset = r[i] as TextAsset;
//			if(asset.name.Contains("sprite_sh"))
//			{
//				SpriteSheetConfig config = new SpriteSheetConfig();
//				MemoryStream stream = new MemoryStream(asset.bytes);
//				BinaryReader reader = new BinaryReader(stream);
//				config.Read(reader);
//			}
//		}
//	}

	public static int ChangeSpriteLoader2(string resPath, Transform t)
	{
		int sum = 0;
		SpriteLoader[] loaders = t.gameObject.GetComponents<SpriteLoader>();
		for(int j = 0; j < loaders.Length; j++)
		{
			SpriteLoader loader = loaders[j];

			Sprite sprite = null;
			for(int k = 0; k < exts.Length; k++)
			{
				string spritePath = resPath + "/" + loader.sprite_path + exts[k];
				sprite = AssetDatabase.LoadAssetAtPath(spritePath, typeof(Sprite)) as Sprite;
				if(sprite != null)
				{
					break;
				}
			}

			if(sprite == null)
			{
				for(int k = 0; k < exts.Length; k++)
				{
					string spritePath = resPath + "/" + Path.GetDirectoryName(loader.sprite_path) + exts[k];
					Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(spritePath);
					for(int u = 0; u < sprites.Length; u++)
					{
						if(sprites[u] is Sprite && sprites[u].name == Path.GetFileName(loader.sprite_path))
						{
							sprite = sprites[u] as Sprite;
							break;
						}
					}

					if(sprite != null)
					{
						break;
					}
				}
			}

			if(sprite == null)
			{
				Debug.LogError(loader.sprite_path);
			}

			Renderer renderer = loader.gameObject.GetComponent<Renderer>();
			if(renderer != null && renderer is SpriteRenderer)
			{
				SpriteRenderer sprenderer = renderer as SpriteRenderer;
				sprenderer.sprite = sprite;
			}
			else
			{
				Image image = loader.gameObject.GetComponent<Image>();
				image.sprite = sprite;
			}
			GameObject.DestroyImmediate(loader, true);
		}

		sum += loaders.Length;

		for(int i = 0; i < t.childCount; i++)
		{
			Transform t2 = t.GetChild(i);
			sum += ChangeSpriteLoader2(resPath, t2);
		}

		return sum;
	}


	public static int UseSpriteLoader2(string resPath, HashSet<string> set, Transform t)
	{
		int sum = 0;
		{
			SpriteRenderer render = t.gameObject.GetComponent<SpriteRenderer>();
			if(render != null && render.sprite != null)
			{
				string texPath = AssetDatabase.GetAssetPath(render.sprite);
				if(set.Contains(texPath))
				{
					Object[] objs = AssetDatabase.LoadAllAssetsAtPath(texPath);
					int spriteNum = 0;
					for(int s = 0; s < objs.Length; s++)
					{
						if(objs[s] is Sprite)
						{
							spriteNum++;
						}
					}

					SpriteLoader loader = t.gameObject.AddComponent<SpriteLoader>();
					loader.sprite_path = texPath.Replace(Path.GetExtension(texPath), "").Replace(resPath + "/", "");
					if(spriteNum > 1)
					{
						loader.sprite_path += "/" + render.sprite.name;
					}

					render.sprite = null;

					sum++;
				}
			}
		}

		{
			Image image = t.gameObject.GetComponent<Image>();
			if(image != null && image.sprite != null)
			{
				string texPath = AssetDatabase.GetAssetPath(image.sprite);
				if(set.Contains(texPath))
				{
					Object[] objs = AssetDatabase.LoadAllAssetsAtPath(texPath);
					int spriteNum = 0;
					for(int s = 0; s < objs.Length; s++)
					{
						if(objs[s] is Sprite)
						{
							spriteNum++;
						}
					}
					
					SpriteLoader loader = t.gameObject.AddComponent<SpriteLoader>();
					loader.sprite_path = texPath.Replace(Path.GetExtension(texPath), "").Replace(resPath + "/", "");
					if(spriteNum > 1)
					{
						loader.sprite_path += "/" + image.sprite.name;
					}
					
					image.sprite = null;
					sum++;
				}
			}
		}

		for(int i = 0; i < t.childCount; i++)
		{
			Transform t2 = t.GetChild(i);
			sum += UseSpriteLoader2(resPath, set, t2);
		}
		
		return sum;
	}

	[MenuItem("Custom/OldProject/ChangeSpriteLoader")]
	public static void ChangeSpriteLoader()
	{
		string[] paths = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];

			GameObject obj = AssetDatabase.LoadAssetAtPath(path, typeof(Object)) as GameObject;
			string resPath = EditorCommonTool.getResPath(path);
			if(ChangeSpriteLoader2(resPath, obj.transform) > 0)
			{
				EditorUtility.SetDirty(obj);
			}
		}

		AssetDatabase.SaveAssets();
	}

	[MenuItem("Custom/OldProject/UseSpriteLoader")]
	public static void UseSpriteLoader()
	{
		string[] paths = Directory.GetDirectories("Assets/", ResourcesEx.IcpResDirName + "", SearchOption.AllDirectories);
		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			string[] filePaths = Directory.GetFiles(path, "*", SearchOption.AllDirectories);

			HashSet<string> set = new HashSet<string>();
			for(int j = 0; j < filePaths.Length; j++)
			{
				if(filePaths[j].Contains(ResourcesEx.dirSymbol + "") && !filePaths[j].EndsWith(".meta"))
				{
					set.Add(filePaths[j].Replace(ResourcesEx.IcpResDirName + "/", "").Replace(ResourcesEx.dirSymbol, '/'));
				}
			}

			string resPath = EditorCommonTool.getResPath(path);
			string[] prefabPaths = Directory.GetFiles(resPath, "*.prefab", SearchOption.AllDirectories);
			for(int k = 0; k < prefabPaths.Length; k++)
			{
				string prefabPath = prefabPaths[k];

				GameObject obj = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(Object)) as GameObject;
				if(obj == null)
				{
					Debug.LogError("load prefab failed:" + prefabPath);
				}
				else if(UseSpriteLoader2(resPath, set, obj.transform) > 0)
				{
					EditorUtility.SetDirty(obj);
				}
			}
		}
		

		
		AssetDatabase.SaveAssets();
	}

	[MenuItem("Custom/OldProject/checkTextSize")]
	public static void checkTextSize()
	{
		string s = "";
		for(int j = 0; j < exts.Length; j++)
		{
			string[] paths = Directory.GetFiles(ConfigTool.bundleDir[0] + "/" + EditorCommonTool.getSheetDirName(BuildTarget.Android), "*" + exts[j], SearchOption.AllDirectories);
			for(int i = 0; i < paths.Length; i++)
			{
				string path = paths[i];
				Texture2D tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
				if(tex.width > 2048 || tex.height > 2048)
				{
					s += path + " " + tex.width + " " + tex.height + "\n";
				}
			}
		}
		
		Debug.LogError(s);
	}

	[MenuItem("Custom/OldProject/checkDll")]
	public static void checkDll()
	{
		string findStr = "Managed";
		byte[] findData = System.Text.Encoding.ASCII.GetBytes(findStr); 
		string[] filePaths = Directory.GetFiles("test_dll", "*", SearchOption.AllDirectories);
		Dictionary<string, HashSet<int>> findMap = new Dictionary<string, HashSet<int>>();
		for(int i = 0; i < filePaths.Length; i++)
		{
			string filePath = filePaths[i];
			byte[] data = CommonUtil.fileToBytes(filePath);
			for(int j = 0; j < data.Length; j++)
			{
				int k = 0;
				for(; k < findData.Length && j + k < data.Length; k++)
				{
					byte t = findData[k];
					byte t1 = data[k + j];
					if(t != t1)
					{
						break;
					}
				}

				if(k == findData.Length)
				{
					HashSet<int> indexMap = null;
					if(!findMap.TryGetValue(filePath, out indexMap))
					{
						indexMap = new HashSet<int>();
						findMap.Add(filePath, indexMap);
					}
					indexMap.Add(j);
				}
			}
		}

		string str = "";
		Dictionary<string, HashSet<int>>.Enumerator enume = findMap.GetEnumerator();
		while(enume.MoveNext())
		{
			str += enume.Current.Key + ":";
			HashSet<int>.Enumerator r = enume.Current.Value.GetEnumerator();
			while(r.MoveNext())
			{
				str += r.Current + ", ";
			}
			str += "\n";
		}

		Debug.LogError(str);
	}

//	[MenuItem("Custom/OldProject/test_bundle")]
//	public static void test_bundle()
//	{
//		AssetBundle bundle = BundleManager.CreateFromFile("Assets/material.unity3d");
//		object[] mats = BundleManager.LoadAll(bundle, typeof(Material));
//		string s = "";
//		for(int i = 0; i < mats.Length; i++)
//		{
//			Material m = mats[i] as Material;
//			s += m.name + "\n";
//		}
//		bundle.Unload(true);
//
//		Debug.Log(s);
//	}

	public static HashSet<string> getSpriteSheetSpritePaths(string pathToData)
	{
		StreamReader sr = new StreamReader(pathToData);
		string t_OrginalPlist = sr. ReadToEnd();
		sr.Close();
		
		//
		XmlDocument xml = new XmlDocument();
		xml.LoadXml(t_OrginalPlist);
		
		// Find the root plist object. If it doesn't exist or isn't a plist node, state so and return null.
		XmlNode plistNode = xml. LastChild;
		if (plistNode.Name != "plist") { Debug.LogError("This is not a plist file: " + " File name"); return null; }
		
		// Get the version number of this plist file. This script was designed to work with version 1.0. If this is an incorrect version, state so and return null
		string plistVers = plistNode.Attributes["version"].InnerText;
		string plistVersSupported = "1.0";
		if (plistVers != plistVersSupported) { Debug.LogError("This is an unsupported plist version: " + plistVers + ". Require version " + plistVersSupported); return null; }
		
		// Get the root plist dict object. This is the root object that contains all the data in the plist file. This object will be the hashtable.
		XmlNode dictNode = plistNode.FirstChild;
		if (dictNode.Name != "dict") { Debug.LogError("Missing root dict from plist file: " + "File name"); return null; }
		
		HashSet<string> paths = new HashSet<string>();
		XmlNodeList nodeList = dictNode.ChildNodes[1].ChildNodes;
		string frameName = null;
		foreach (XmlNode node in nodeList)
		{
			if(frameName == null)
			{
				frameName = node.InnerText;
				string ext = Path.GetExtension(frameName);
				frameName = frameName.Replace(ext, "");
				paths.Add(frameName);
			}
			else
			{
				frameName = null;
			}
		}
		
		return paths;
	}
		
//	[MenuItem("Custom/OldProject/test_region")]
//	public static void test_region()
//	{
//		Msg.map_region r0 = new Msg.map_region();
//		r0._x = 0;
//		r0._y = 0;
//		r0._w = 1.5f;
//		r0._h = 0.5f;
//
//		Msg.map_region r1 = new Msg.map_region();
//		r1._x = 1;
//		r1._y = 0;
//		r1._w = 0.5f;
//		r1._h = 0.5f;
//
//		string log = "";
//		List<Msg.map_region> rList = new List<Msg.map_region>();
//		ServerMapLayer.excludeRegion(r0, r1, rList);
//		for(int i = 0; i < rList.Count; i++)
//		{
//			Msg.map_region r = rList[i];
//			log += "region_" + i + ": " + "(" + r._x + ", " + r._y + " # " + r._w + ", " + r._h + ")\n";
//		}
//
//		Debug.Log(log);
//	}
}